简体   繁体   English

Python从文本文件获取字符串,并检查文本文件中是否有匹配的单词

[英]Python Getting string from text file, and checking if there's matched word in the text file

None of my tried attempts were succeed, i tried to change the lines, change the text file lines. 我的尝试都没有成功,我尝试更改行数,更改文本文件行。 What I'm doing here, is trying to search for the name, which user puts inside input("Whats your name?"), and if the system founds the name in the text file, it prints a message. 我在这里所做的是尝试搜索名称,该用户将其放入input(“ Whats your name?”)中,如果系统在文本文件中找到该名称,则会打印一条消息。 Screenshot of the code, and CMD. 代码和CMD的屏幕截图。

# Atidarom text'ini faila, kuriam visi ban nickai
Banlistas = open('Listas_BAN.txt', mode='r').readlines()
name = input("~ Please enter Your name below\n")
clear()
# Checking if there's name in the BANLIST Which is currently in Listas_BAN
if name in Banlistas:
    print('your name {n} is in the list'.format(n=name))
else:
    print('your name {n}, was not found in the list'.format(n=name))

The system is not finding the name, but it is in the text file. 系统找不到名称,但是在文本文件中。 enter image description here enter image description here 在此处 输入图像描述在 此处 输入图像描述

PS - Sorry for my English, I'm also new to python PS-对不起,我的英语,我也是python的新手

EDIT : enter image description here 编辑: 在此处输入图片描述

name = input("~ Please enter Your name below\n")
ban_path = 'Listas_BAN.txt' # be sure to replace by the full path

with open(ban_path , mode='r', encoding='utf-8') as f:
    if name in f.read():
        print('your name {n} is in the list'.format(n=name))
    else:
        print('your name {n}, was not found in the list'.format(n=name))

A few things here: 这里有几件事:

  • you should use the with keyword to open your file: it will take care of the opening/closing of your file 您应该使用with关键字打开文件:它将负责文件的打开/关闭
  • adding the encoding could be helpful to manage special characters 添加编码可能有助于管理特殊字符
  • f.read() will return the full content of the file, no need to iterate over the lines f.read()将返回文件的全部内容,而无需遍历各行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM