我是python的新手,所以玩起来不错,但是我正在尝试编写一个程序,以帮助我编写在不同国家/地区要做的事情的列表。应该先询问哪个国家/地区做什么,然后将该活动放在该国家/地区的标题下。文本文档的格式如下:
Bolivia:
- salt pans
Ecuador:
Peru:
Spain:
此代码肯定有效,但我强烈感觉有一种简单的方法可以实现此目的。
f = open('travel.txt', 'r+')
contents = f.readlines()
contents = ''.join(contents)
country = input('Country: ')
length = len(cnty)+2
activity = input('Activity: ')
index = contents.find(country+':\n') + length
content = contents[:index] + '- ' + activity + '\n' + contents[index:]
g = open('travel.txt', 'w')
g.write(content)
我尝试附加文本文档,但是根据我的理解,它总是附加到末尾。还尝试过使用f.seek()
并在某个索引处进行写操作,但是这似乎会覆盖,并且找不到阻止它的方法。
为任何帮助喝彩:)
答案 0 :(得分:1)
您可以做的是像这样用dict of country
创建一个list of activities
-
lines = f.readlines()
current_country = ''
countries = {}
for country in lines:
if ":" in country:
current_country = country.replace(":", "").replace("\n", "").strip()
countries[current_country] = []
else:
countries[current_country].append(country.replace("-", "").strip())
您将以这种方式获得的数据将是一个决定。例如,如果数据为-
Bolivia:
- salt pans
- black
Ecuador:
- green
- white
Peru:
- blue
- black
Spain:
- grey
您将拥有一个字典--
{'Spain': ['grey'], 'Bolivia': ['salt pans', 'black'], 'Peru': ['blue', 'black'], 'Ecuador': ['green', 'white']}
现在要占领一个国家,您要做的就是-
countries['Bolivia']
将为您提供西班牙的活动清单
['salt pans', 'black']
由于这是命令,因此只需O(1)
即可检索一个国家/地区的活动列表
答案 1 :(得分:0)
而不是将文件编辑为字符串,而是将其保留为列表并进行编辑。当您去写文件时,将其转换回纯文本。这样,您就不必使用字符串索引了,而是使用了更健壮的列表索引,在计算字符串的确切索引时不易出错。
此外,在处理文件时,应使用如下所示的with
语句。 with
语句将自动为您打开和关闭文件,并使代码看起来更简洁。
最后一件事是使用.strip()
方法删除不必要的换行符。您也可以执行.replace("\n", "")
。
with open("travel.txt", "r") as travel_file:
# read into list without newline characters
file_contents = travel_file.read().splitlines()
# .strip() will remove whitespace and newline characters
country = input("Country: ").strip()
activity = input("Activity: ").strip()
country_index = file_contents.index(country)
file_contents[country_index] = country + " - " + activity
with open("travel.txt", "w") as outfile:
outfile.write("\n".join(file_contents))