我在Python中遇到了“collections”模块的问题

时间:2018-06-04 19:54:13

标签: python collections

我需要翻译句子(从txt文件中打开),使得单词中的字母重复次数与单词本身中遇到的次数相同。

示例:

“我需要喝一杯”必须变成:“我喝了一杯”

这是代码。我知道这很糟糕:

import collections

c = collections.Counter()

words_title = []

new_word = ''

new_word2 = ''

with open("file.txt", "r", encoding = "utf-8-sig") as file:                   
    reading = file.read()
    splitted = reading.split()

words_title = [word.title() for word in reading]

for word in words_title:
    for wor in word:
        for wo in word:
            c[wo] += 1
            new_word += word

for word2 in new_word:
    word2 = word2 * c[word2]
    new_word2 += word2

print(c)
print(new_word)
print(new_word2)

3 个答案:

答案 0 :(得分:0)

以下是对我想要做的事情的尝试:

from collections import Counter

start_string = '  coconuts taste great '

words = start_string.strip().split() # get single words from string

for word in words: # loop over individual words
    c = Counter(word) # count letters
    new_word = ''
    for w in word: # loop over letters in the original word
        new_word += w*c[w] # write the new word
    print new_word

#ccooccoonuts
#ttastte
#great

答案 1 :(得分:0)

sentence = "I need a drink"
words = sentence.split()

out_sentence = ""

for word in words:
    for letter in word:
        for _ in range(word.count(letter)):
            out_sentence += letter
    out_sentence += " "

out_sentence = out_sentence[:-1]

print(out_sentence)

答案 2 :(得分:0)

这里是Dux答案中的一行内容,但使用生成器表达式并在最后连接所有字符序列而不是每次迭代:

from collections import Counter

s = 'I need a drink, coconut'

print(''.join(c * n[c] for w in s.split() for n in (Counter(w + ' '),) for c in w + ' '))
# Output: I neeeed a drink, ccooccoonut

请注意第二个' for'只迭代一次,以便将Counter对象分配给n;这个小技巧确保只为每个单词w创建一个新的Counter对象,而不是为每个单词c创建。