[英]Pulling information from a .txt file in python based on a user input
I have a list in the form of a .txt file that i need to pull certain information from based on a user input.我有一个 .txt 文件形式的列表,我需要根据用户输入从中提取某些信息。
Latitude Longitude City Province/State Country
82°30N 62°20W Alert Nunavut Canada
81°36N 16°40W Nord Greenland Denmark
79°59N 85°56W Eureka Nunavut Canada
this is a snippet of the list.这是列表的一个片段。 I understand how to pull the information out and put it into a list.我了解如何提取信息并将其放入列表中。 I need to find the city that the user inputs and then output the linked lat and lon of the city.我需要找到用户输入的城市,然后输出城市的链接纬度和经度。 I am new to python so not sure what process i could use to solve this.我是 python 的新手,所以不确定我可以使用什么过程来解决这个问题。
Instead of putting it into a list I would put the output into a pandas.Dataframe
(or just a dict
).我不会将其放入列表中,而是将输出放入pandas.Dataframe
(或只是dict
)。 Assuming your text-file is separated with tabs, has a header and each row is of equal length, you can do:假设您的文本文件用制表符分隔,有一个标题并且每行长度相等,您可以执行以下操作:
df = pd.read_csv('yourfile.txt',delimiter='\t')
print('Enter name of City:')
name = input()
print('Latitude:', df[df['City'] == name]['Latitude'].values, 'Longitude:', df[df['City'] == name]['Longitude'].values)
If you execute the script and type the city name it will be stored as a string into name
.如果您执行脚本并输入城市名称,它将作为字符串存储到name
。 After that we print the Long/Lat values selecting the corresponding city from the DataFrame
.之后,我们打印从DataFrame
选择相应城市的 Long/Lat 值。
simple pythonic way, hope it may help you简单的pythonic方式,希望它可以帮助你
city = input("Enter City name")
with open('your text file') as file:
print(file.readline().split()[:3])
for line in file.readlines():
if line.split()[2] == city:
print(line.split()[:3])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.