gpt4 book ai didi

python - 读取并检查文件中的连续单词

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:16 24 4
gpt4 key购买 nike

我想读取文件中的单词,例如,检查单词是否为“1”,如果单词为 1,我必须检查下一个单词是否为“two”。在那之后我必须做一些其他的任务。你能帮我检查连续出现“1”和“二”吗?

我用过

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]

但它不起作用。

最佳答案

处理连续项的最简单方法是使用 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

目前,您的索引(ii+1)在每个单词(即字符)内,而不是列表中的单词。

关于python - 读取并检查文件中的连续单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22297946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com