Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按字符串的一部分查找字符串_Python - Fatal编程技术网

Python 按字符串的一部分查找字符串

Python 按字符串的一部分查找字符串,python,Python,是否可以在文件中按部分查找行 例如: 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")

是否可以在文件中按部分查找行

例如:

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") 

 
使用,您可以执行以下操作:

重新导入
strs=(
“我是个好孩子”,
“我是个好女孩”,
“我是坏男孩”,
“我是真正的好孩子”)
对于STR中的s:
如果重新匹配(“我是+男孩”,s):
打印(“是的,是的,是的”)
其他:
打印(“实际上不是”)
印刷品

Yes, it is, yeah
It's actually not
Yes, it is, yeah
Yes, it is, yeah

这是我发现有效的方法

我有一个文本文件,其中有以下两行(我知道您有):

我写了这篇文章(附有解释其工作原理的注释):

输出为:

Line 1
Line 2

这意味着文本文件中的两行中都有“我是那个”和“男孩”。

您可以使用
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

有两条线。你想找哪一个?不,这个不行<
中的code>只对精确的子字符串有效。@BuddyBob我需要找到一个有数千行的文件,因为我不知道缺少的单词确切在哪里,所以我们指定
\\w+
来查找行吗?你可以用
+
替换
\\w+
。我已经更新了我的答案。
Line 1
Line 2
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