问题
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