我正在做一个python练习,它必须打开并读取爱丽丝梦游仙境的文本文件,通过计算字数填充字典,然后写出该文件。看在我的份上,这行不通。有什么建议吗??在
f = open('/Users/yongcho822/Desktop/alice.txt', 'r')
count = {}
for line in f:
for word in line.split():
# remove punctuation
word = word.replace('_', '').replace('"', '').replace(',', '').replace('.', '')
word = word.replace('-', '').replace('?', '').replace('!', '').replace("'", "")
word = word.replace('(', '').replace(')', '').replace(':', '').replace('[', '')
word = word.replace(']', '').replace(';', '')
# ignore case
word = word.lower()
# ignore numbers
if word.isalpha():
if word in count:
count[word] = count[word] + 1
else:
count[word] = 1
keys = list(count.keys())
keys.sort()
# save the word count analysis to a file
out = open('/Users/yongcho822/Desktop/alice.txt', 'w')
for word in keys:
out.write(word + " " + str(count[word]))
out.write('\n')
print("The word 'alice' appears " + str(count['alice']) + " times in the book.")
您确定要将写入名为
alice.txt
的文件,而该文件也是输入文件的名称吗?在检查您的输入文件(
Desktop/alice.txt
)以确保您没有意外地覆盖它!请为输出文件使用其他名称,例如output.txt
。在另一个小问题是第二个for
循环的缩进,但我认为这只是你问题的格式问题。否则,你的代码对我有用。我在我使用的文本中找到了167x
Alice
。在去掉标点符号的一个更简单的方法是:
相关问题 更多 >
编程相关推荐