简体   繁体   English

将此字符串转换为 Python 中的列表

[英]Convert this String to a List in Python

I'm new to Python and I try to convert following txt to two lists, splitting Country from Capital.我是 Python 的新手,我尝试将以下 txt 转换为两个列表,将 Country 与 Capital 分开。

Afghanistan | Kabul
Albania | Tirana
Algeria | Algiers
...

I tried:我试过了:

with open("/FILE.txt") as f:
    lines = f.read().split("| ")

If you have a string like string="Kabul Albania" so use Split如果你有一个像 string="Kabul Albania" 这样的字符串,那么使用 Split

a="Kabul Albania"
print(a.split(" ")) #OUTPUT WILL BE ['Kabul', 'Albania']

You are reading the entire file into one big string, then splitting that on the separator.您正在将整个文件读入一个大字符串,然后将其拆分为分隔符。 The result will look something like结果看起来像

lines = ['Afghanistan', 'Kabul\nAlbania', 'Tirana\nAlgeria', 'Algiers']

If you want to split the file into lines, the splitlines function does that.如果你想把文件分成几行, splitlines function 会这样做。

with open("/FILE.txt") as f:
    lines = f.read().splitlines()

But if you want to split that one list into two lists, perhaps try something like但是如果你想把那个列表分成两个列表,也许试试类似

countries = []
capitals = []
with open("/FILE.txt") as f:
    for line in f:
        country, capital = line.rstrip("\n").split(" | ")
        countries.append(country)
        capitals.append(capital)

A better solution still might be to read the values into a dictionary.更好的解决方案可能仍然是将值读入字典。

capital = {}
with open("/FILE.txt") as f:
    for line in f:
        country, city = line.rstrip("\n").split(" | ")
        capital[country] = city

As an aside, you almost certainly should not have a data file in the root directory of your OS.顺便说一句,你几乎可以肯定不应该在你的操作系统的根目录中有一个数据文件。 This location is reserved for administrative files (or really, in practical terms, just the first level of the directory tree hierarchy).这个位置是为管理文件保留的(或者实际上,实际上,只是目录树层次结构的第一级)。

This should work, you had the first part right just need to add the result to two different list这应该可行,您的第一部分是正确的,只需要将结果添加到两个不同的列表中

country = []
capitals = []
with open("FILE.txt", "r") as f:
    for line in f:
        result = line.strip().split("|")
        country.append(result[0].strip())
        capitals.append(result[1].strip())

print(country)
print(capitals)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM