2017-05-10 24 views
-1

我最近开始学习Python,并且直到现在,所有内容看起来都非常直观。遍历单词列表以检查是否有任何以Python开头的给定字符串

我有一个文本文件,它有几行数据。我遍历每一行,将它分解成单词,现在我想要遍历给定行上的每个单词,以检查它是否以给定字符串开头,如果是,则将单词更改为其他单词。

到目前为止,我有:

with open('test_inputfile.txt','r') as f: 
for line in f: 
    words = line.split('","') 
    for word in words: 
     if word.startswith('spam'): 
      # change given word 

但我似乎无法访问的word.startswith()功能这不起作用。

我相信它一定很容易做到,因为到目前为止的其他一切都非常简单!

谢谢。

+4

你可能有一个空的迭代器,因为你应该分割为'',''而不是''“,'''' –

+0

@MosesKoledoye不是空的,而是只有一个元素:整个'line'。 – schwobaseggl

+0

@MosesKoledoye文本文件在单词 – user1949213

回答

0

你可以试试这个:

f = open('test_inputfile.txt').readlines() 
f = [i.strip('\n').split(',') for i in f] 
for line in f: 
    for word in line: 
     if word.startswith('spam'): 

现在,F存储包含各行中的所有单词列表的列表。

0

如果您使用CSV数据,这可能会很有用。如果是这种情况,请将您的分组更改为line.split(',')。否则见下文。

使用startswith函数时,不需要实际分割线条,因为您只关心线条的起始位置。见here的详细信息,在startswith功能

with open('test_inputfile.txt', 'r') as f: for line in f: if line.startswith('spam', 0, 4): # take action

这有效地检查,如果这个词“垃圾邮件”是在位置0至4

一切顺利:)

+0

也许我不是'我想检查每个WORD是否以'垃圾邮件'开头,而不是每行。 感谢您的帮助! – user1949213

0

你可能会忘记去掉每行中的最初/最后一个双引号。但我强烈建议您使用csv模块来处理CSV数据:

import csv 
with open('test_inputfile.txt','r') as f: 
    reader = csv.reader(f, delimiter=',', quotechar='"') 
    # both params are the default values anyway 
    for row in reader: 
    for word in row: 
     if word.startswith('spam'): 
     # do stuff 
+0

感谢您的回答,但是,我得到了与我原来的代码相同的问题:I不能使用单词 – user1949213

0

你有一个这样的文件:

"toast","eggs","bacon" 
"orangejuice","spamandtoast","bagels" 

读取文件:

with open("test_inputfile.txt", "r") as fs: 
    for lines in fs: 
     line = lines.split(",") 
     for word in line: 
      word = word.replace('"','') # removes the quotes 
      if word.startswith("spam"): 
       print word 

您也可以创建一个在开始的空列表wordlist = []中,并将每个单词添加到列表中。

wordlist.append(word)

更好地利用csv模块。

+0

的.startswith()函数这与我的代码基本相同,但我不能使用'words.startswith()'。 – user1949213

+0

请输入您的输入的一点点文本。 – bhansa

+0

看起来像这样: '“吐司”,“鸡蛋”,“培根” “orangejuice”,“spamandtoast”,“百吉饼”' (其中'orangejuice'开始一个新行) 我想找到'spamandtoast',然后,例如,将其更改为'酸奶' – user1949213

相关问题