【发布时间】:2019-01-31 11:17:47
【问题描述】:
所以我编写了一个程序(尽管很丑),它计算给定输入中的单词数和每个唯一单词的实例。
我的问题是我想将它用于歌词,但大多数歌词集都带有多个段落分隔符。
我的问题是:如何让用户输入带有分段符的歌词并将输入减少到单个字符串?
这是我目前的代码:
Song = {}
lines = []
while True:
line = input("")
if line:
lines.append(line)
else:
break
string = '\n'.join(lines)
def string_cleaner(string):
string = string.lower()
newString = ''
validLetters = " abcdefghijklmnopqrstuvwxyz"
newString = ''.join([char for char in string if char in validLetters])
return newString
def song_splitter(string):
string = string_cleaner(string)
words = string.split()
for word in words:
if word in Song:
Song[word] += 1
else:
Song[word] = 1
预期输入:
Well, my heart went "boom"
When I crossed that room
And I held her hand in mine
Whoah, we danced through the night
And we held each other tight
And before too long I fell in love with her
Now I'll never dance with another
(Whooh)
Since I saw her standing there
Oh since I saw her standing there
Oh since I saw her standing there
期望的输出:
This song has 328 words.
39 of which are unique.
This song is 11% unique words.
('i', 6)
('her', 4)
('standing', 3)
.... etc
【问题讨论】:
-
为什么需要将输入减少到单个字符串?您可以将所有行附加到列表并遍历它。
-
我是编程新手,所以我可能不知道所有的捷径,但我现在的问题是,当我尝试输入带有分段符的行时(在 IDLE 中)IDLE 读取段落分隔符作为输入的结尾。例如 IDLE 会读到:“但是当我回到你身边时,我会发现你所做的事情会让我感觉很好//你知道我整天工作是为了让你有钱给你买东西而且听到你的声音是值得的说你会给我一切”只是“但是当……到……感觉还好”
-
也许您应该在问题中提供示例输入和所需的输出。
-
用户输入:嗯,当我穿过那个房间时,我的心“砰砰”跳动起来,我握着她的手哇,我们跳了一夜,我们紧紧地抱在一起,不久我就摔倒了爱上了她 现在我再也不会和另一个人跳舞了(哇)自从我看到她站在那里 哦,因为我看到她站在那里 哦,因为我看到她站在那里 期望的输出类似于:这首歌有 328 个单词。其中39个是独一无二的。这首歌是 11% 的独特词。 ('i', 6) ('her', 4) ('standing', 3)....等
-
打印的属性无关紧要...这首歌很长... “哇,我们彻夜跳舞”被视为用户只“输入”了休息前的台词。我正在想办法解决这个问题。
标签: python string list dictionary split