0

所以我制作了一个名称生成器/查找器,所以对于查找命令,我想在带有行号的 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")

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

编辑:我找到了一种方法,如果您想为更多遇到问题的人回复,您可以回复!

4

4 回答 4

0

尝试这个:

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))
于 2021-08-21T14:46:42.877 回答
0

你可以尝试这样的事情:

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如果您希望搜索区分大小写,则可以删除该标志。

于 2021-08-21T15:32:59.063 回答
0

if "namefilled" in name : 

print("找到了")

于 2021-08-21T14:42:05.883 回答
0

如果你有 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。

于 2021-08-21T14:53:16.287 回答