在文本文件python中查找一个字符串的多个实例

2024-10-01 11:30:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个文本文件中找到一个字符串的多个实例,但我只能找到第一个实例的方法。我试过各种各样的while和for循环都没有用,我被困在答案中。在python中实现这一点的最有效方法是什么?在

movinf = open("movinf.txt", "a")
        match = re.search('"string":([^,]+)', name)
        if match:
            result = match.group(1)
            movinf.write(result + "\n")
        else:
            pass
        movinf.close()

Tags: 实例方法字符串答案retxtforsearch
3条回答

你可以试试re.findall()

p = re.pattern('"string":([^,]+)')
print p.findall(name)

以下程序使用简单的文件和列表操作:

str1 = raw_input("Enter the string you want to search : ")
with open("C:\\Users\\priyank\\Desktop\\movinf.txt","r") as movinf:
    listp = movinf.readlines()
count =0
for i in range(0, len(listp)):
    if str1 in listp[i]:
        # do something
        count=count+1
print "number of word exist in file :" + str(count)

只运行一次块,因此只得到一个结果。使用re.findall代替:

match = re.findall('"string":([^,]+)', name)
if len(match) > 0:
    movinf.write("\n".join(match))
movinf.close()

相关问题 更多 >