Python 如何计算多行中的单词实例?
我是python新手,我正在慢慢地学习它。我正在尝试编写一个简单的单词计数器,它可以跨多行跟踪单词的实例。我试图将该行放入一个列表中,然后跟踪字典中的每个列表点,同时在字典更新时从列表中删除每个单词。到目前为止,我已经:Python 如何计算多行中的单词实例?,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,我是python新手,我正在慢慢地学习它。我正在尝试编写一个简单的单词计数器,它可以跨多行跟踪单词的实例。我试图将该行放入一个列表中,然后跟踪字典中的每个列表点,同时在字典更新时从列表中删除每个单词。到目前为止,我已经: dic = {} count = '' liste = line.split() listes = liste[0] num = 0 while line: while not liste: listes = liste[0] if listes in di
dic = {}
count = ''
liste = line.split()
listes = liste[0]
num = 0
while line:
while not liste:
listes = liste[0]
if listes in dic:
count = str(dic[listes])
count = count.rstrip("]")
count = count.lstrip("[")
count = int(count) + 1
liste.pop(0)
else:
skadoing = 1
dic [listes] = [skadoing]
line = input("Enter line: ")
for word in sorted(dic):
print(word, dic[word])
运行时,它当前输出以下内容:
Enter line: which witch
Enter line: is which
Enter line:
which ['']
我需要它输出以下内容:
Enter line: which witch
Enter line: is which
Enter line:
is 1
which 2
witch 1
liste
是输入行中的单词列表,listes
是我试图在字典中更新的单词
有什么想法吗?我相信这就是你想要实现的目标:
dic = {}
line = input("Enter line: ")
while line:
for word in line.split(" "):
if word not in dic:
dic[word] = 1
else:
dic[word] +=1
line = input("Enter line: ")
for word in sorted(dic):
print(word, dic[word])
输出:
Enter line: hello world
Enter line: world
Enter line:
hello 1
world 2
{'this': 1, 'is': 2, 'a': 1, 'test': 1, 'for': 1, 'which': 3, 'witch': 1, 'and': 1, 'because': 1, 'of': 1}
如果您真的想自己实现这一点并计算字数,那么最好使用
defaultdict
:
from collections import defaultdict
sentence = '''this is a test for which is witch and which
because of which'''
words = sentence.split()
d = defaultdict(int)
for word in words:
d[word] = d[word]+ 1
print(d)
输出:
Enter line: hello world
Enter line: world
Enter line:
hello 1
world 2
{'this': 1, 'is': 2, 'a': 1, 'test': 1, 'for': 1, 'which': 3, 'witch': 1, 'and': 1, 'because': 1, 'of': 1}
也许您可以使用collections软件包来完成这项工作:-
from collections import Counter
line = input("Enter line: ")
words = line.split(" ")
word_count = dict(Counter(words))
print(word_count)
希望这有帮助 为什么
which=2
和witch=1
,而输入只是which
?这不是一个好主意。我建议您使用python内置(from collections import Counter
),它统计列表中出现的单词,这样您就可以拆分它,工作就完成了!格式化问题代码。Amin Guermazi,如何使用counter()函数?似乎可以正常工作,但不能使用空格。有什么想法吗?