【问题标题】:Appending a list that tallies the length of words附加一个计算单词长度的列表
【发布时间】:2011-11-02 17:37:57
【问题描述】:

我正在从一个文本文件中提取单词,删除每个单词的 \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]

这归结为:

  • 计算单词的长度,例如n
  • 在 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

【问题讨论】:

  • 第一个也是最重要的问题是您使用的是什么语言?
  • 该死的,Python,我不知道为什么我把它从标题中删除了,对不起,让我更新问题
  • 只需使用python 标记即可 - 您无需在问题标题中添加“Python”。
  • 您的代码有什么不正常的地方?
  • @eldarerathis python 标签已经存在,但不是很清楚。

标签: python list append


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我认为您代码中的错误行是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
    

    【讨论】:

    • 好答案谢谢!但是有一个问题,使用 tally = [0] * 20 会使之前的 tally 定义变得毫无用处,不是吗?再次感谢。
    • 是的,这就是我注释掉这些行的原因,这样做更容易
    • “之前的计数定义”已在此处明确注释掉。这是论坛上使用的一种技术,说“我在此处添加的代码是我已注释掉的代码的更简单(或更惯用)的直接替换”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 2012-02-02
    • 2016-05-21
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多