如何在txt文件中查找某个string/name?

How to find a certain string/name in a txt file?

所以我正在命名 generator/finder,所以对于 find 命令,我想在 txt 文件中找到带有行号的那个名字!那么如何找到带有行号的名称呢?

line = 0

names = open(r"names.txt", "r")
name1 = names.readlines()

uname = input("Please enter the name you want to find: ")
for name in name1:
  try:
    print(name)
    print(line)
    if name == uname:
      print(f"Found name: {name} \nLine No. {line + 1}")
    else:
      line = line + 1
  except:
    print("Unable to process")

但它似乎不起作用,除非您在文件中写入姓氏,否则它会起作用。那么可以提供任何帮助吗?

编辑:我找到了一种方法,如果你想让更多人 运行 解决这个问题,你可以回复!

if "namefilled" in name : 

print("找到了")

试试这个:

with open("names.txt", "r") as f:
    file_contents = names.read().splitlines()

uname = input("Please enter the name you want to find: ")

for line, row in enumerate(file_contents):
    if uname in row:
        print('Name "{0}" found in line {1}'.format(uname, line))

如果你有 Python 3.4+,你可以使用 pathlib。非常方便的库。

此外,上下文管理很有用。

# Using pathlib
from pathlib import Path

# https://docs.python.org/3/library/fnmatch.html?highlight=fnmatch#module-fnmatch
import fnmatch

# Create Path() instance with path to text file (can be reference)
txt_file = Path(r"names.txt")

# Gather input
uname = input("Please enter the name you want to find: ")

# Set initial line variable
line = 0

find_all = False

# Use context maangement to auto-close file once complete.
with txt_file.open() as f:
    for line in f.readlines():
        # If python 3.8, you can use assignment operator (:=)
        if match_list := fnmatch.filter(line, uname) is not None: # Doe not match substring.
        
            number_of_names = len(match_list)

            name_index = [i for i, element in enumerate(line.split()) for word in match_list if word == element]

            print(f"""
            {number_of_names} name{"s" if number_of_names > 0 else ""} found on line {line} at position {name_index}.
            """.strip())

    line += 1

根据该线程中有关匹配完整字符串与子字符串的一些其他评论进行编辑以包含 fnmatch。

您可以尝试这样的操作:

import re

search_name = input("Enter the name to find: ")

with open("names.txt", "r") as f:
    for line, row in enumerate(f.read().splitlines()):
        if re.findall('\b'+search_name+'\b', row, flags=re.IGNORECASE):
            print('Name "{0}" found in line {1}'.format(search_name, line))

如果您希望搜索区分大小写,您可以删除 flags=re.IGNORECASE 标志。