“我对”有意见;“收藏”;Python中的模块

“我对”有意见;“收藏”;Python中的模块,python,collections,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:

我需要重新造句(从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)

下面是我想你想做的一个尝试:

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

这是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”仅迭代一次,以便将计数器对象分配给
n
;这个小把戏确保只为每个单词
w
创建一个新的计数器对象,而不是为每个字符
c

创建一个新的计数器对象,您询问的是代码的哪一部分?你期望它做什么,它做什么来代替,你被困在哪里试图修复它?我很确定
对于word中的wor:for word中的wo:
不是一件有用的事情,但是我不知道你想要它做什么,所以我不知道如何修复它。确切地说,是一个中间部分。在我的示例中,它在2个字母的位置使用了4个字母(如“cccooooccccooout”)。我希望单词是“ccooccoonut”。你对嵌套循环所做的是在每对字符上循环。例如,如果
word
'abc'
,则实际上是在
'aa',ab',ac',ba',bb',bc',ca',cb',cc'上循环。除了你不再使用
wor
之外,你实际上只是在
上循环“a”、“b”、“c”、“a”、“b”、“c”、“a”、“b”、“c”
。那该怎么办呢?我建议不要把文件操作包括在问题中,因为这是不相关的。这个问题应该简化为使用
start\u string=“whatever”
,而不是从文件加载。对你和我们来说,用这种方式测试也会更容易。我有一个完整的句子。我应该把它分成单词,然后把单词分成字母,只有这样我才能在字母上循环。这正是我需要的!非常感谢正是我需要的!非常感谢
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