从Python3中的文件列表中查找字符串
我试图在我创建的两个单独的列表中找到一个名称,并进行函数检查以确定它是否存在。我知道它正在检查列表,并且我已经打印出了列表,以确保它被正确存储,但它一直给我错误声明,在列表中找不到该名称。这是我的代码从Python3中的文件列表中查找字符串,python,python-3.x,list,search,Python,Python 3.x,List,Search,我试图在我创建的两个单独的列表中找到一个名称,并进行函数检查以确定它是否存在。我知道它正在检查列表,并且我已经打印出了列表,以确保它被正确存储,但它一直给我错误声明,在列表中找不到该名称。这是我的代码 def readBoyFiles(): boyfile = 'BoyNames.txt' boyList = [] with open(boyfile, 'r') as lis: for line in lis: boyList.ap
def readBoyFiles():
boyfile = 'BoyNames.txt'
boyList = []
with open(boyfile, 'r') as lis:
for line in lis:
boyList.append(line)
return boyList
def readGirlFiles():
girlfile = 'GirlNames.txt'
girlList = []
with open(girlfile, 'r') as names:
for line in names:
girlList.append(line)
return girlList
def nameInput():
name = input('Please enter the name you would like to search: ')
list1 = readBoyFiles()
list2 = readGirlFiles()
findName(name, list1)
findName(name, list2)
def findName(name, list):
if name in list:
print('This name is among the most popular!')
else:
print('This name is not among the most popular.')
nameInput()
当我输入像print(list1)这样的print语句时,它会给我这种格式的名称,['Jacob\n',…],当我测试它时,它会打印出我的else语句,而不管我输入什么。我也尝试过用索引函数检查它,如果我尝试的话,它会告诉我“Jacob”不在列表中。我觉得我必须忽略一些东西,因为我已经编写了类似的代码,这些代码可以正常工作,除了不同的数据类型之外,这几乎是它的镜像。记得去掉字符串!它删除前导和尾随空格。从技术上讲,“Jacob”不在列表中,因为“Jacob\n”在列表中
代码的一个更具Python风格的版本
def load_list(file_name):
with open(file_name, 'r') as f:
return [name.strip() for name in f.readlines()]
def get_lists_and_user_input():
name = raw_input('Please enter the name you would like to search: ')
boys_list = load_list('popular_boys.txt')
girls_list = load_list('popular_girls.txt')
return boys_list, girls_list, name
def check_name(name, lst, _type):
if name in lst:
print('The name {} is a popular {} name'.format(name, _type))
else:
print('The name {} is NOT a popular {} name'.format(name, _type))
boys, girls, _name = get_lists_and_user_input()
check_name(_name, boys, 'boys')
check_name(_name, girls, 'girls')
BoyNames.txt中的男孩姓名是如何存储的?如果您有一个逐行的名称,那么在每个名称的末尾将添加一个换行符
\n
到名称中,因此当您在文件指针上枚举时,您正在读取lis
您正在逐行读取所有内容,包括换行符。在类似boyList.append(line.replace(“\n”,”)
def load_list(file_name):
with open(file_name, 'r') as f:
return [name.strip() for name in f.readlines()]
def get_lists_and_user_input():
name = raw_input('Please enter the name you would like to search: ')
boys_list = load_list('popular_boys.txt')
girls_list = load_list('popular_girls.txt')
return boys_list, girls_list, name
def check_name(name, lst, _type):
if name in lst:
print('The name {} is a popular {} name'.format(name, _type))
else:
print('The name {} is NOT a popular {} name'.format(name, _type))
boys, girls, _name = get_lists_and_user_input()
check_name(_name, boys, 'boys')
check_name(_name, girls, 'girls')