2011-11-02 56 views
0

我正在從文本文件中取詞,剝離\ 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]

那麼,如果被剝離的單詞列表包含5倍的7個字母的單詞和3分的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爲length_of_words [N-1]

我真的停留在如何實質上增加1項的值(因爲它仍然有1個字母的單詞是第0項開始)一個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 
+0

您使用的是哪種語言? –

+0

第一個也是最重要的問題是你在用什麼語言? – Kevin

+0

該死的,Python,我不知道爲什麼我將它從標題中刪除,對不起,讓我更新這個問題 –

回答

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 
+0

很好的答案,謝謝!但是有一個問題,使用tally = [0] * 20表示tally以前的定義是無用的嗎?再次感謝。 –

+0

是的,這就是爲什麼我評論這些行,這樣做更容易 –

+1

「以前的Tally定義」已在此明確註釋。這是一個在論壇上使用的技術,「我在這裏添加的代碼是一個更簡單的(或者更習慣的),替代我已經註釋過的代碼」。 –

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,這裏有一些小的代碼改進(更Python風格):

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 
相關問題