Skip to main content
 首页 » 编程设计

python之在 Python 中解析多行

2025年05月04日13dyllove98

我目前正在学习 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 

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

感谢任何提示。谢谢。

请您参考如下方法:

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

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']