2016-02-12 110 views
0

我一直有这个循环,应该遍历并保存与本书中的所有单词列表的麻烦。Python循环,遍历一个字符串:'int'对象是不可迭代的

我得到的错误是:'int' object is not iterable

def create_word_dict() 
    word_list = open("mobydick.txt", "r") 
    all_list = word_list.read() 
    all_list = all_list.split() 
    word_list.close() 
    for index in len(all_list): 
     all_list[index] = parseString(all_list[index]) 
    return all_list 

# Removes punctuation marks from a string 
def parseString (st): 
    s = "" 

    for ch in st: 
     if ch.isalpha() or ch.isspace(): 
      s += ch 
     else: 
      s += "" 
    return s #return was outside code block 
+0

它说'int'对象是不可迭代的 – Needhelp

+0

我编辑你的帖子来修复所有的缩进。你究竟有什么问题? – abe

回答

2

我猜你想

for index in range(len(all_list)): 
    all_list[index]=parseString(all_list[index]) 

因为for i in 5:意味着什么在Python(因为一个int不能重复),但是,对于i in range(5)确实是一个有效的语句,因为范围可以重复.. 。

但它可能会更好,只是遍历对象直接

new_list = [] 
for word in all_list: 
    new_list.append(parseString(word)) 

甚至更​​好的只是做一个列表理解

new_list = [parseString(word) for word in all_list] 
+1

很高兴在这里展示所有的例子... +1 –

+0

好吧,我怀疑它的__all__的例子; P但大多数常见的至少 –

+0

好吧得到它谢谢! – Needhelp

0

您可以通过使用一些Python的内置方法加快了很多东西:

from string import ascii_lowercase as lower, ascii_uppercase as upper 
from string import digits, punctuation 

# create a translation table which 
# makes the string lowercase and 
# replaces all digits and punctuation with spaces 
TRANS = str.maketrans(
    lower + upper +   digits + punctuation, 
    lower + lower + " " * len(digits + punctuation) 
) 

def get_word_list(filename): 
    with open(filename) as inf: 
     return inf.read().translate(TRANS).split() 

words = get_word_list("mobydick.txt") 

为了比较的缘故,我的机器上这在0.11秒内加载Gutenberg版本的Moby Dick(220231字)。

+0

好吧,谢谢! – Needhelp

相关问题