我想读取文件中的单词,并说例如,检查单词是否为“1”,如果单词为1,我必须检查下一个单词是否为“2”。之后我还要做一些其他任务。你可以帮我连续检查“1”和“2”的出现。
我用过
filne = raw_input("name of existing file to be proceesed:")
f = open(filne, 'r+')
for word in f.read().split():
for i in xrange(len(word)):
print word[i]
print word[i+1]
但它不起作用。
答案 0 :(得分:4)
处理连续项目的最简单方法是zip
:
with open(filename, 'r') as f: # better way to open file
for line in f: # for each line
words = line.strip().split() # all words on the line
for word1, word2 in zip(words, words[1:]): # iterate through pairs
if word1 == '1' and word2 == 'crore': # test the pair
目前,您的索引(i
和i+1
)位于每个单词(即字符)内,而不是列表中的单词。
答案 1 :(得分:0)
我想你要从文件中打印两个连续的单词, 在你的代码中,如果那是你想要做的事情,那么你将迭代每个字符而不是文件中的每个单词。 您可以通过以下方式执行此操作:
f = open('yourFileName')
str1 = f.read().split()
for i in xrange(len(str1)-1): # -1 otherwise it will be index out of range error
print str1[i]
print str1[i+1]
如果您想检查某个单词是否存在并想要检查旁边的单词,请使用
if 'wordYouWantToCheck' in str1:
index=str1.index('wordYouWantToCheck')
现在您有所需单词的索引,您可以使用str1[index+1]
检查旁边的单词。
但'index'函数只返回第一次出现的单词。要在此完成您的意图,您可以使用'枚举'功能。
indices = [i for i,x in enumerate(str1) if x == "1"]
这将返回包含所有出现的单词“1”的索引的列表。