如何在文本文件中查找多个字符串?

How do I find multiple strings in a text file?

我需要找到文本文件中找到的所有字符串并将其大写。我已经找到了如何找到字符串,但是如果你能帮我打印,得到多个是我的问题,给定的字符串在我的代码中,将非常感谢。

import os
import subprocess

i = 1
string1 = 'biscuit eater'

# opens the text file

# if this is the path where my file resides, f will become an absolute path to it
f = os.path.expanduser("/users/acarroll55277/documents/Notes/new_myfile.txt")

# with this form of open, the wile will automatically close when exiting the code block
txtfile = open (f, 'r')

# print(f.read()) to print the text document in terminal
# this sets variables flag and index to 0

flag = 0
index = 0

# looks through the file line by line
for line in txtfile:
    index += 1

#checking if the sting is in the line or not
    if string1 in line:
        flag = 1
        break 
# checking condition for sting found or not
if flag == 0:
    print('string ' + string1 + ' not found')
else:
    print('string ' + string1 + ' found in line ' + str(index))

您可以使用str.replace-method。因此,在找到字符串的行中,写入 line.replace(string1, string1.upper(), 1)。最后一个 1 仅使函数替换字符串的 1 次出现。

或者您将文本文件作为字符串读取并在整个字符串上使用 replace 方法。这为您节省了尝试手动查找事件的麻烦。在那种情况下,你可以写

txtfile = open(f, 'r')
content = txtfile.read()
content = content.replace(string1, string1.upper())

我相信你的方法会奏效,但它非常冗长而且不是很 Pythonic。试试这个:

import os, subprocess

string1 = 'biscuit eater'

with open(os.path.expanduser("/users/acarroll55277/documents/Notes/new_myfile.txt"), 'r+') as fptr:

    matches = list()
    [matches.append(i) for i, line in enumerate(fptr.readlines()) if string1 in line.strip()]
    fptr.read().replace(string1, string1.title())

    if len(matches) == 0: print(f"string {string1} not found")

    [print(f"string {string1} found in line {i}") for i in matches]

现在,这将为文件中 每个 出现的字符串打印一条消息。此外,由于 with 语句,文件得到安全处理并在脚本末尾自动关闭。