如何将txt文件中的文本转换为数据框?

时间:2019-07-19 06:53:39

标签: python python-3.x pandas dataframe

拥有一个值

的txt
baker 
1102, new york ,USA
newyork
USA
52206354601

Orthop 
4Th Line,Main Road,Pincode-522007
delhi
India
52365967

如何将其转换为这样的有效数据框

Name          address                         city       country        pincode 

baker    1102, new york ,USA                  newyork      USA          52206354601
Orthop  4Th Line,Main Road,Pincode-522007     delhi        India         52365967

1 个答案:

答案 0 :(得分:-1)

使用以下python代码:

data = { "Name": [], "address": [], "city": [], "country": [], "pincode": [] }

with open('test.txt', 'r+') as file:
    content = file.read()
    for line in content.split('\n\n'):
        if len(line) > 1:
            print(line)
            name, address, city, country, pincode = line.split('\n')
            data["Name"].append(name)
            data["address"].append(address)
            data["city"].append(city)
            data["country"].append(country)
            data["pincode"].append(pincode)


print(data)