【发布时间】:2019-03-14 23:27:18
【问题描述】:
该段落包含空格和随机标点符号,我在 for 循环中通过 .replace 删除了它们。然后我通过 .split() 将段落放入列表中以获取 ['the', 'title', 'etc']。然后我做了两个函数计算单词来计算每个单词,但我不希望它计算每个单词,所以我创建了另一个函数来创建一个唯一列表。但是,我需要创建一个 for 循环来打印出每个单词以及它说了多少次,输出是这样的
The word The appears 2 times in the paragraph.
The word titled appears 1 times in the paragraph.
The word track appears 1 times in the paragraph.
我也很难理解 for 循环的本质。我读到我们应该只使用 for 循环进行计数,而使用 while 循环进行任何其他事情,但 while 循环也可用于计数。
paragraph = """ The titled track “Heart Attack” does not interpret the
feelings of being in love in a serious way,
but with Chuu’s own adorable emoticon like ways. The music video has
references to historical and fictional
figures such as the artist Rene Magritte!!.... """
for r in ((",", ""), ("!", ""), (".", ""), (" ", "")):
paragraph = paragraph.replace(*r)
paragraph_list = paragraph.split()
def count_words(word, word_list):
word_count = 0
for i in range(len(word_list)):
if word_list[i] == word:
word_count += 1
return word_count
def unique(word):
result = []
for f in word:
if f not in result:
result.append(f)
return result
unique_list = unique(paragraph_list)
【问题讨论】:
-
如果您打算拆分数据,我认为您不想去掉空格。
-
开头和结尾有两个空格,所以 (" ", "") 只是删除了两个空格。是的,对不起,我应该提到这一点。
-
您忘记删除引号和换行符
-
set()创建一个集合并将其丢弃。您需要将其分配给变量才能使用它。您也可以从unique()返回集合本身。无需转换为列表,因为您也可以枚举和查找集合中的元素。 -
def unique(word): result = [] for f in word: if f not in result: result.append(f) return result似乎没有 set() 就可以工作
标签: python string python-3.x loops