1

I have a list in the form of a .txt file that i need to pull certain information from based on a user input.

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.

2
  • Is every entry on one line, and is every field guaranteed to be separated by a space? Commented Sep 26, 2018 at 21:46
  • yes, each entry has its own line and they are separated by a tab('\t') Commented Sep 27, 2018 at 0:45

2 Answers 2

1

Instead of putting it into a list I would put the output into a pandas.Dataframe (or just a 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. After that we print the Long/Lat values selecting the corresponding city from the DataFrame.

Sign up to request clarification or add additional context in comments.

1 Comment

That works but i'm not allowed to use modules in this assignment.
0

simple pythonic way, hope it may help you

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.