是否可以通过文件的一部分在文件中找到行
例如:
I'm the good boy
I'm the bad boy
I'm the really good boy
我可以通过搜索 I'm the boy
而不写 good
或 bad
来找到该行吗
我需要抓住三行
我试过了
str = "iam good boy"
if "iam boy" in str:
print ("yes")
else:
print ("no")
答案 0 :(得分:0)
使用 RegEx,您可以执行以下操作:
import re
strs = (
"I'm the good boy",
"I'm the good girl",
"I'm the bad boy",
"I'm the really good boy")
for s in strs:
if re.match("I'm the .+ boy", s):
print("Yes, it is, yeah")
else:
print("It's actually not")
印刷品
Yes, it is, yeah
It's actually not
Yes, it is, yeah
Yes, it is, yeah
答案 1 :(得分:0)
这是我发现有效的方法。
我有一个文本文件,里面有这两行(我知道你有):
I'm the good boy
I'm the bad boy
我写的(用注释解释它是如何工作的):
with open("testing.txt", 'r') as file:#Open the text file, do stuff and then close it when done
row_counter = 0
for row in file: #Go through each line in the file
row_counter +=1
if "I'm the" in row: #Check to see if a line in your file if it has "I'm the"
if "boy" in row: #Narrows down to find a line that also contains "boy"
print(f"Line {row_counter}") #In forms you which line(s) have "I'm the" and "boy" in them
输出为:
Line 1
Line 2
表示文本文件中的两行都包含“I'm the”和“boy”。
答案 2 :(得分:0)
您可以使用 re.search
来找到匹配项。还 enumerate
保留索引并且只返回 yes 是所有匹配发生。
import re
stro = "iam good boy"
target = "iam boy"
def finder():
for i,e in enumerate(target.split()):
if re.search(e, stro):
if i == len(target.split()) - 1:
return("yes")
else:
return("no")
finder()
# Yes