使用Python阅读/写入文件并使用字典进行WordCount列表

2024-09-27 19:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个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.")

Tags: intxtforcountlineopenkeysout
2条回答

您确定要写入名为alice.txt的文件,而该文件也是输入文件的名称吗?在

检查您的输入文件(Desktop/alice.txt)以确保您没有意外地覆盖它!请为输出文件使用其他名称,例如output.txt。在

另一个小问题是第二个for循环的缩进,但我认为这只是你问题的格式问题。

否则,你的代码对我有用。我在我使用的文本中找到了167xAlice。在

去掉标点符号的一个更简单的方法是:

word=word.translate(None, string.punctuation)

相关问题 更多 >

    热门问题