【问题标题】:How to find a certain string/name in a txt file?如何在 txt 文件中查找某个字符串/名称?
【发布时间】:2021-10-22 16:53:54
【问题描述】:

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

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

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

【问题讨论】:

  • readlines() 的输出包括每行末尾的换行符。所以你需要去掉它,否则你会将"Steve""Steve\n" 进行比较,它们并不相等。
  • 不要使用空的except。始终将它与您要捕获的错误一起使用。无论如何,您希望代码中出现什么样的错误?

标签: python random generator txt


【解决方案1】:

你可以试试这样的:

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 标志。

【讨论】:

  • 我改变了一些东西,它奏效了!感谢您的帮助!
【解决方案2】:

如果你有 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 每个其他 cmets 关于匹配完整字符串与子字符串的内容。

【讨论】:

    【解决方案3】:

    试试这个:

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

    【讨论】:

    • 我喜欢with 语句和enumerate,但使用in 进行比较并不是最好的主意。如果我想搜索“Carl”但文件中没有“Carl”但“Carlos”程序仍会告诉我它找到了“Carl”。
    • 好点,我想如果行只包含名称,那么您可以使用==,否则需要更聪明的方法(例如,如果行包含“Carlosnumber1234”,您将无法轻松搜索“卡尔”)。
    【解决方案4】:

    if "namefilled" in name : 
    

    print("找到")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      相关资源
      最近更新 更多