【发布时间】:2014-11-23 12:35:17
【问题描述】:
我正在尝试在 Python 3.4.1 中制作一个简单的单词计数器程序,用户将在其中输入以逗号分隔的单词列表,然后在示例文本文件中分析这些单词的频率。
我目前不知道如何在文本文件中搜索输入的单词列表。
首先我尝试过:
file = input("What file would you like to open? ")
f = open(file, 'r')
search = input("Enter the words you want to search for (separate with commas): ").lower().split(",")
search = [x.strip(' ') for x in search]
count = {}
for word in search:
count[word] = count.get(word,0)+1
for word in sorted(count):
print(word, count[word])
这导致:
What file would you like to open? twelve_days_of_fast_food.txt
Enter the words you want to search for (separate with commas): first, rings, the
first 1
rings 1
the 1
如果这有什么可做的,我猜这个方法只给了我输入列表中单词的计数,而不是文本文件中单词输入列表的计数。于是我尝试了:
file = input("What file would you like to open? ")
f = open(file, 'r')
lines = f.readlines()
line = f.readline()
word = line.split()
search = input("Enter the words you want to search for (separate with commas): ").lower().split(",")
search = [x.strip(' ') for x in search]
count = {}
for word in lines:
if word in search:
count[word] = count.get(word,0)+1
for word in sorted(count):
print(word, count[word])
这没有给我任何回报。事情是这样的:
What file would you like to open? twelve_days_of_fast_food.txt
Enter the words you want to search for (separate with commas): first, the, rings
>>>
我做错了什么?我该如何解决这个问题?
【问题讨论】:
标签: python word-count word-frequency