提取新lin后的行

2024-04-24 03:49:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件

Country1
city1
city2

Country2
city3
city4

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


Tags: 文件方法方式国家文本文件country2country1city1
3条回答
$countries = array();
$cities = array();
$gap = false;
$file = file('path/to/file');
foreach($file as $line)
{
  if($line == '') $gap = true;
  elseif ($line != '' and $gap) 
  {
    $countries[] = $line;
    $gap = false;
  }
  elseif ($line != '' and !$gap) $cities[] = $line;
}
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

输出:

^{pr2}$

如果要将这些写入文件:

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))
f = open('b.txt', 'r')
status = True
country = []
city = []
for line in f:
    line = line.strip('\n').strip()
    if line:
        if status:
            country.append(line)
            status = False
        else:
            city.append(line)
    else:
        status = True

print country
print city


output :

>>['city1', 'city2', 'city3', 'city4']
>>['Country1', 'Country2']

相关问题 更多 >