【问题标题】:how to make python read file from notepad and give the value如何让python从记事本读取文件并给出值
【发布时间】:2020-07-01 17:58:10
【问题描述】:

大家好,所以我有这个包含国家和首都列表的记事本。 然后我想输入国家名称以显示首都,所以这就是我感到困惑的地方。

country.txt
malaysia, vietnam, myanmar, china, sri lanka, japan, brazil, usa, australia, thailand, russia, uk
kuala lumpur, hanoi, yangon, beijing, colombo, tokyo, rio, washington, canberra, bangkok, moscow, london

这是国家和首都的记事本文件

f = open(r'C:\Users\User\Desktop\country.txt')
count = 0
for line in f:
    line = line.rstrip('\n')
    rec = line.split(',')
    count = count + 1

ctry = input('\nEnter country name: ')
ctry = ctry.lower()

for i in country:
    if ctry == country[i]:
        print ('country:', ctry)
        print ('capital:', capital[i])
        break
else:
    print ('country not in the list')

这是我不知道该怎么做才能让它工作的地方。

我希望输出是这样的

Enter country name: vietnam 
Country: vietnam 
Capital:  hanoi 

当列表中没有国家时

Enter country name: france 
Country not in the list

【问题讨论】:

  • 你的 country 变量中有什么?你遇到了什么错误?
  • 和capital[i]一样,这里没有定义capital
  • Traceback (most recent call last): File "C:\Users\User\Desktop\Q3.py", line 13, in <module> for i in country: NameError: name 'country' is not defined

标签: python list for-loop input notepad


【解决方案1】:

首先,以下是您的代码无法运行的一些原因以及一些建议:

  • 您未定义变量 country 或 capital,因此您将输入与空值进行比较,这将引发错误,因为未定义变量。
  • 如果你打开一个文件,你应该在操作后关闭它,建议最好使用with。
  • 请参阅 this 了解 for 循环的工作原理,因为您试图索引 country[i],知道 i 是一个元素而不是整数索引。

不过,你可以试试这个:

with open(r'C:/Users/User/Desktop/country.txt') as f:
    lines=f.read().splitlines()
    countries=lines[0].strip().split(', ')
    cities=lines[1].strip().split(', ')
count = 0

print(countries)
print(cities)


ctry = input('\nEnter country name: ')
ctry = ctry.lower()

for i in countries:
    if i == ctry:
        print ('country:', ctry)
        print ('capital:', cities[countries.index(i)])
        break
else:
    print ('country not in the list')

输出:

countries
>>>['malaysia', 'vietnam', 'myanmar', 'china', 'sri lanka', 'japan', 'brazil', 'usa', 'australia', 'thailand', 'russia', 'uk']

cities
>>>['kuala lumpur', 'hanoi', 'yangon', 'beijing', 'colombo', 'tokyo', 'rio', 'washington', 'canberra', 'bangkok', 'moscow', 'london']

>>>'\nEnter country name: ' uk
>>>country: uk
>>>capital: london

【讨论】:

  • 谢谢你。我需要在 for 循环上做更多的工作和练习。
  • 不客气,不用担心,继续练习! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
相关资源
最近更新 更多