在新行之后提取行

Myt*_*yth 0 php python regex vim parsing

我有一个类似的文本文件

Country1
city1
city2

Country2
city3
city4
Run Code Online (Sandbox Code Playgroud)

我想把国家和城市分开.这有什么快速的方法吗?我正在考虑一些文件处理然后提取到不同的文件,这是最好的方式还是可以快速完成一些正则表达式?

rob*_*ing 5

countries=[]
cities=[]
with open("countries.txt") as f:
    gap=True
    for line in f:
        line=line.strip()
        if gap:
            countries.append(line)
            gap=False
        elif line=="":
            gap=True
        else:
            cities.append(line)
print countries
print cities
Run Code Online (Sandbox Code Playgroud)

输出:

['Country1', 'Country2']
['city1', 'city2', 'city3', 'city4']
Run Code Online (Sandbox Code Playgroud)

如果你想将这些写入文件:

with open("countries.txt","w") as country_file, open("cities.txt","w") as city_file:
    country_file.write("\n".join(countries))
    city_file.write("\n".join(cities))
Run Code Online (Sandbox Code Playgroud)