【问题标题】:Python - Removing paragraph breaks in inputPython - 删除输入中的段落中断
【发布时间】: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


【解决方案1】:

以下示例代码从每一行中提取所有单词(仅限英文字母)并处理它们(计算单词的数量,并检索每个唯一单词的实例)。

import re

MESSAGE = 'Please input a new line: '
TEST_LINE = '''
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 well well
Oh since I saw her standing there
'''

prog = re.compile(r'\w+')

class UniqueWordCounter():

    def __init__(self):
        self.data = {}

    def add(self, word):
        if word:
            count = self.data.get(word)
            if count:
                count += 1
            else:
                count = 1
            self.data[word] = count


# instances of each unique word
set_of_words = UniqueWordCounter()
# counts the number of words
count_of_words = 0

def handle_line(line):
    line = line.lower()
    words = map(lambda mo: mo.group(0), prog.finditer(line))
    for word in words:
        global count_of_words
        count_of_words += 1
        set_of_words.add(word)

def run():
    line = input(MESSAGE)

    if not line:
        line = TEST_LINE

    while line:
        '''
        Loop continues as long as `line` is not empty
        '''

        handle_line(line)

        line = input(MESSAGE)

    count_of_unique_words = len(set_of_words.data.keys())
    unique_percentage = count_of_unique_words / count_of_words

    print('-------------------------')
    print('This song has {} words.'.format(count_of_words))
    print('{} of which are unique.'.format(count_of_unique_words))
    print('This song is {:.2%} unique words.'.format(unique_percentage))

    items = sorted(set_of_words.data.items(), key = lambda tup: tup[1], reverse=True)
    items = ["('{}', {})".format(k, v) for k, v in items]

    print('\n'.join(items[:3]))
    print('...')

run()

如果你想处理其他语言的歌词,你应该看看这个link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 2015-12-16
    相关资源
    最近更新 更多