python - 如何在 .txt 文件中搜索字符串并打印字符串所在的行?(Python)
问题描述
上面的问题。我正在尝试在 Python 3 的控制台内创建一个通讯录,并且我正在尝试实现一个“搜索”命令,但我尝试过的一切都没有奏效。我也没有在互联网上找到任何有用的东西。
f = open("C:/Users/Yonas/Documents/PythonProject.txt", "a")
entry = input()
i = 0
def add():
print("Please type in the name of the person you want to add.")
in2 = input()
f.write(in2 + " | ")
print("Please type in the location of the person you want to add.")
in3 = input()
f.write(in3 + " | ")
print("Please type in some additional information.")
in4 = input()
f.write(in4 + "\n")
def search():
line_number = 0
print("Please type in the name of the person you're looking for.")
inSearch = input()
list_of_results = list(f)
# The code should be here
if entry.startswith("add"):
add()
if entry.startswith("search"):
search()
希望你能理解我的问题。
解决方案
原始片段的略微修改版本:
contact_book_path = "collection.txt"
def add():
with open(contact_book_path, "a") as contact_book_fp:
contact = ""
name = input("Please type in the name of the person you want to add.\n")
contact += name + " | "
location = input("Please type in the location of the person you want to add.\n")
contact += location + " | "
info = input("Please type in some additional information.\n")
contact += info + "\n"
contact_book_fp.write(contact)
def search():
with open(contact_book_path, "r") as contact_book_fp:
name_search = input(
"Please type in the name of the person you're looking for.\n"
)
for line_no, contact in enumerate(contact_book_fp.readlines()):
name, location, info = contact.split(" | ")
if name == name_search:
print("Your contact was found at line " + str(line_no))
return
print("Your contact was not found! :(")
entry = input("What kind of operation would you like to do (add/search)?\n")
if entry.startswith("add"):
add()
if entry.startswith("search"):
search()
我建议您在真正需要时打开它以进行正确的操作,而不是在附加模式下打开文件。因此,对于附加add
和读取search
.
在search
打开文件并要求搜索名称后的函数中,您可以使用标准file.readlines()
方法遍历文件中的行。我还使用该enumerate
函数将运行索引与行一起获取,以后可以将其用作行号。
将所有这些放在一起,您基本上可以以任何您想要的方式增强查找逻辑。
推荐阅读
- vuejs2 - `apollo-link-state` 和 `vuex`,当我使用 `vue-apollo` 时,我应该使用哪一个来进行状态管理?
- c# - 防止对php登录系统的恶意攻击
- spring-mvc - 如何从 jsp 的下拉菜单中获取多个选定的值并在控制器方法中使用它
- c# - 将字节数组转换为一定长度的数组段
- amazon-web-services - s3api - 按大小查询似乎不起作用
- angular - 自定义组件内的离子网格
- javascript - 如何找出 Chrome 违规的来源
- javascript - 需要搜索框过滤器 javascript
- java - Android layerlist 在不同的手机上不起作用
- javascript - 如何在多个 React Native 组件中保持变量的当前值