附加一个列出单词长度的列表

时间:2011-11-02 17:37:58

标签: python list append

我正在从文本文件中删除单词,删除\ n的每个单词并从这些单词中创建一个新列表。

现在我需要系统地逐字逐句查找单词的长度,然后在该单词长度的数量上加1,即我将从一个空的计数开始:

length_of_words = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

然后,如果剥离的单词列表包含5x 7个字母单词和3x 2个单词单词,我最终会得到:

length_of_words = [0,3,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

归结为:

  • 计算单词的长度,例如Ñ
  • 为length_of_words [n-1]添加一个到length_of_words(因为它仍然以1个字母的单词作为第0个项目开始)

我真的被困在如何将列表中1项的值基本上增加1,而不是仅将1添加到列表的末尾。

我现在所拥有的是:

lines = open ('E:\Python\Assessment\dracula.txt', 'r'). readlines ()

stripped_list = [item.strip() for item in lines]

tally = [] #empty set of lengths
for lengths in range(1,20):
    tally.append(0)

print tally #original tally

for i in stripped_list:
    length_word = int(len(i))
    tally[length_word] = tally[length_word] + 1
print tally

2 个答案:

答案 0 :(得分:2)

collections.Counter类对这类事情有帮助:

>>> from collections import Counter
>>> words = 'the quick brown fox jumped over the lazy dog'.split()
>>> Counter(map(len, words))
Counter({3: 4, 4: 2, 5: 2, 6: 1})

您在问题中发布的代码工作正常,所以我不确定您被困在哪里。

FWIW,这里有一些小代码改进(更多Pythonic风格):

stripped_list = 'the quick brown fox jumped over the lazy dog'.split()

tally = [0] * 20
print tally #original tally

for i in stripped_list:
    length_word = len(i)
    tally[length_word] += 1
print tally

答案 1 :(得分:0)

我认为代码中的错误行是tally[length_word],您忘记添加- 1

我还对您的代码进行了一些更改,以使其更加pythonic

#lines = open ('E:\Python\Assessment\dracula.txt', 'r'). readlines ()

#stripped_list = [item.strip() for item in lines]

with open('/home/facundo/tmp/words.txt') as i:
    stripped_list = [x.strip() for x in i.readlines()]

#tally = [] #empty set of lengths
#for lengths in range(1,20):
#    tally.append(0)

tally = [0] * 20

print tally #original tally

for i in stripped_list:
    #length_word = int(len(i))
    word_length = len(i)
    #tally[length_word] = tally[length_word] + 1
    if word_length > 0:
        tally[word_length - 1] += 1

print tally