1

我目前正在学习 Python,我需要编写一个程序来确定一首诗中出现次数最多的单词。困扰我的问题是将一首诗的一行解析成一个包含诗词的单列表。当我解决它时,我将毫不费力地确定出现次数最多的单词。

我可以通过反复调用 input() 来访问这首诗的行,最后一行包含三个字符###。

所以,我写道:

while True:
   y = input()
   if y == "###":
     break
   y = y.lower()
   y = y.split()

和输入:

Here is a line like sparkling wine
Line up now behind the cow
###

得到结果:

['here', 'is', 'a', 'line', 'like', 'sparkling', 'wine']
['line', 'up', 'now', 'behind', 'the', 'cow']

如果我尝试调用 y[0],我会得到:

here
line

如何在同一个变量中连接两个列表,或者如何将每一行分配给不同的变量?

任何提示表示赞赏。谢谢。

4

2 回答 2

5

您需要添加y到现有列表,使用list.extend()

words = []
while True:
   y = input()
   if y == "###":
     break
   y = y.lower()
   y = y.split()
   words.extend(y)

现在words是一个列表,其中包含用户输入的行的所有单词。

演示:

>>> words = []
>>> while True:
...    y = input()
...    if y == "###":
...      break
...    y = y.lower()
...    y = y.split()
...    words.extend(y)
... 
Here is a line like sparkling wine
Line up now behind the cow
###
>>> print(words)
['here', 'is', 'a', 'line', 'like', 'sparkling', 'wine', 'line', 'up', 'now', 'behind', 'the', 'cow']
于 2013-06-09T08:58:55.983 回答
3
words = []

while True:
   y = input()
   if y == "###":
     break
   words.extend(y.lower().split())

from collections import Counter
Counter(words).most_common(1)

整个代码可以压缩成以下一行:

Counter(y.lower() for x in iter(input, '###') for y in x.split()).most_common(1)

例如。

>>> sys.stdin = StringIO.StringIO("""Here is a line like sparkling wine
Line up now behind the cow
###""")
>>> Counter(y.lower() for x in iter(input, '###') for y in x.split()).most_common(1)
[('line', 2)]

根据要求,没有任何imports

c = {} # stores counts
for line in iter(input, '###'):
    for word in line.lower().split():
        c[word] = c.get(word, 0) + 1 # gets count of word or 0 if doesn't exist

print(max(c, key=c.get)) # gets max key of c, based on val (count)

为了不必再次通过字典来查找最大单词,请在进行过程中跟踪它:

c = {} # stores counts
max_word = None
for line in iter(input, '###'):
    for word in line.lower().split():
        c[word] = c.get(word, 0) + 1 # gets count of word or 0 if doesn't exist
        if max_word is None:
            max_word = word
        else:
            max_word = max(max_word, word, key=c.get) # max based on count       

print(max_word)
于 2013-06-09T09:01:59.433 回答