python - 在文件中搜索一行并将结果显示在带有文本的单独行上
问题描述
我有一个 txt 文件,我想搜索一个“id”。文件中的每一行包含 5 个字段(id、name、age、height、weight)。如果 id 搜索找到匹配项,我想在匹配行中显示每个字段,如下所示:
x 'player/s have been found:'
print('Player ID: ', id)
print('Player name: ', name)
print('Age: ', age)
print('Height: ', height)
print('Weight: ', weight)
到目前为止,我只能将匹配的行打印为一行,而不能将各个字段拉到不同的打印行上。任何帮助将不胜感激!
这是我到目前为止所拥有的,但 python 似乎无法读取任何匹配项..
def search_enter_id(): '''函数允许用户从 Players.txt 文件中搜索玩家 ID'''
# Create a bool variable to use as a flag
found = False
# Get search value
my_string = input('Please enter the player ID you want to search: ')
# Open a file for reading
player_file = open('Players.txt', 'r')
# Read the first records ID field
id_field = player_file.readline()
# Read the rest of the file
while id_field != '':
# Read the name field
name_field = player_file.readline()
# Read Age field
age_field = player_file.readline()
#Read Height field
height_field = player_file.readline()
#Read weight field
weight_field = player_file.readline()
# Strip the \t\t from fields
id_field = id_field.rstrip('\t\t')
name_field = name_field.rstrip('\t\t')
age_field = age_field.rstrip('\t')
height_field = height_field.rstrip('\t\t')
weight_field = weight_field.rstrip('\n')
# Determine whether this record matches the search value
if id_field == my_string:
# Display the record
print('Player ID: ', id_field)
print('Player name: ', name_field)
print('Age: ', age_field)
print('Height: ', height_field)
print('Weight: ', weight_field)
print()
# Set the found flag to true
found = True
# Read the next ID field
id_field = player_file.readline()
# Close the file
player_file.close()
# If the search value was not found in the file
# display a message
if not found:
print('That ID was not found in the file.')
解决方案
匹配一行后,将其拆分。
array = line.split('xxx')
* 用你的分隔符替换 xxx
现在你可以使用你的数组来取出各个字段。
推荐阅读
- windows - 在 Windows 10 Go v1.12.5 上不允许使用内部包
- javascript - 使用 async/await 时调用堆栈的工作
- shell - 如何比较 Unix 文本文件中的行并将它们添加到另一个文本文件中?
- firebase - 如何在 JOIN 结构中使用 UNNEST?
- nlp - 特殊字符训练 NLP 模型
- virtual-machine - 尝试使用 miniedit 创建应使用 mqtt 流量的虚拟拓扑
- linux - Kubernetes 如何在 docker 容器中工作
- javascript - 通过键配对计算键值的总和,对数组对象的数组进行排序
- eclipse - 在 Windows 10 上的 Eclipse 下运行的 GAE 抛出错误
- c# - 无法解析引用'System.Object System.Configuration.IConfigurationSectionHandler ...有人遇到同样的错误吗?