Python alphanumeric

时光毁灭记忆、已成空白 提交于 2019-12-13 08:55:30

问题


Problem:

I have to go through text file that has lines of strings and determine about each line if it is alphanumeric or not. If the line is alphanumeric print for example "5345m345ö34l is alphanumeric"

Example of the text file:

5345m345ö34l 

no2no123non4 

%#""SGMSGSER 

My code is as follows:

file = open('file.txt','r')
data = file.readlines()

for i in data:
    i.strip()
    if (i.isalnum()):
        print (i, 'is alphanumeric')
    else:
        print (i, 'not alphanumeric')
    file.close()

We can see that the first and second line is alphanumeric but the program doesn't work?


回答1:


try this and see if this working -

file = open('file.txt','r')
data = file.readlines()

for i in data:
    stripped_line = i.strip()
    if (stripped_line.isalnum()):
       print (stripped_line, 'is alphanumeric')
    else:
       print (stripped_line, 'not alphanumeric')
file.close()



回答2:


EDIT

From your original post you want to treat latin characters (i.e. those with accents) as valid alphanumeric input. In order to do this you should load the original file in unicode and when testing for alphanumeric qualities you should convert the accented letters to normal alphabetic. This will do that:

# -*- coding: utf-8 -*-
import unicodedata
import codecs

file = codecs.open('file.txt','rb', encoding="utf-8")
data = file.readlines()
for i in data:
    i = i.strip()
    converted_data = ''.join((c for c in unicodedata.normalize('NFD', i) if unicodedata.category(c) != 'Mn'))
    if (converted_data.isalnum()):
        print (i, 'is alphanumeric')
    else:
        print (i, 'not alphanumeric')
file.close()


来源:https://stackoverflow.com/questions/44394647/python-alphanumeric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!