[英]How to search for the word in each line of a file and print the next value of it in python
[英]How to find a word in a text file and print another that is in the next line in Python
我有一个充满文本的文本文件,每次某个单词出现在一行中时,下一行是我想在另一个文本文件中打印的数字。 我一直在使用 enumerate 来查找单词 NEXT 的数字,但我想要下一行中的那个。 例如,这是文本文件:
Line 1: Hello bye
Line 2: 23
Line 3: Adios bye
Line 4: 45
我希望程序找到单词 bye 并打印 23 和 45。现在我只能找到 Hello 并打印 bye。 如何让它打印以下行? 谢谢你。
您可以搜索每一行,然后移动到下一行,如下所示:
with open('text.txt','r') as f:
for line in f:
phrase = 'bye'
if phrase in line: #if the phrase is present
next(f) #move to next line
你可以用下面的行做任何你想做的事情; 如果您要查找数字,则可以使用.isdigit()
假设该行仅包含数字。
一种可能的替代解决方案是使用正则表达式:
import re
def hasNumber(string):
return bool(re.search(r'\d', string)) #returns true/false
with open('text.txt','r') as f:
for line in f:
if re.match('bye',line): #if it contains the word "bye"
newline = next(f) #declare the next line
if hasNumber(newline): #if that line contains any numbers
number = re.compile(r'\d') #find those numbers
print(''.join(number.findall(newline)[:])) #print those numbers
如果第二个变量与第一个变量匹配,则re.match
function 将返回 true(尽管这并非严格正确,因为它仅在条件句中以这种方式起作用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.