我编写了这段代码,但在编写结果时遇到了麻烦。当前代码仅写入50,000个单词的文件中的最后一个单词!
我的另一个问题是,如何使此代码通过Excel文件读取,并将结果写入新的Excel文件?我有两列,一列是英语(列名:EN),另一列是阿拉伯语(列名:AR)。
代码:
filename = 'words.txt'
try:
with open('G:\\Nalpha.txt', 'r') as fileobject:
contents = fileobject.read()
except FileNotFoundError:
message = 'Sorry, the file ' + filename + ' connot be found.'
print(message)
else:
words = contents.split()
number_words = len(words)
print('The file ' + filename + ' has approximatley ' + str(number_words) + ' words.')
alphabet = ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
unique_words = []
'''Word Frequency'''
words = contents.split()
for word in words:
if word not in unique_words:
unique_words.append(word)
else:
pass
for i in unique_words:
word_frequencey = words.count(i)
print(i, ':', word_frequencey)
textfile = open('G:\\Nalphadone.txt', 'w')
textfile.write(word)
textfile.close()
我认为您在.txt文件中仅获得一个元素的原因是,您每次在最后一个for循环周期中都打开它。写入模式在调用时会擦除具有相同名称的旧文件。尝试在for循环之前打开文件!