[英]How to convert data in txt form into a list in python
例如,這是我在txt
文件中的數據:
Chair
Table
Planks
Door
每個由一個新行分隔。 那么我如何將它轉換成一個list
,這樣它的 output 就會像這樣:
['Chair', 'Table', 'Planks', 'Door']
每次我嘗試將其轉換為list
時,它也會在list
中打印換行符。
我通過新行字符不斷添加來嘗試這段代碼
for line in filen:
setn.add(line)
for items in setn:
items.replace(" ", "")
with open('test.txt', 'r') as f:
print(f.read().split())
['Chair', 'Table', 'Planks', 'Door']
編輯
您最初的嘗試是添加整line
。 您需要strip
或rstrip
每一line
。 因為每一line
末尾都有一個換行符( \n
)。
setn = set()
with open('test.txt', 'r') as filen:
for line in filen:
setn.add(line.rstrip())
print(setn)
{'Chair', 'Planks', 'Table', 'Door'}
請注意, set
沒有重復項,要將set
轉換為list
,您只需使用list(set)
如果您願意,您可以將代碼簡化為生成器理解:
with open('test.txt', 'r') as filen:
setn = set(x.rstrip() for x in filen)
列表理解(類似於生成器理解)-https://www.w3schools.com/python/python_lists_comprehension.asp
試試 python 拆分方法。
your_list.split("\n")
a="""
Chair
Table
Planks
Door
"""
帶換行符
print([i for i in a.split('\n')])
output - ['', 'Chair', 'Table', 'Planks', 'Door', '']
沒有換行符(避免換行符)
print([i for i in a.split('\n') if i != ""])
output - ['Chair', 'Table', 'Planks', 'Door']
以讀取模式打開文件
my_file = open("file1.txt", "r")
讀取文件
data = my_file.read()
當看到換行符 ('\n') 時替換結束拆分文本。
data_into_list = data.split("\n")
print(data_into_list)
my_file.close()
output:
['椅子','桌子','木板','門']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.