[英]Converting the text file into a string or list
我的文本文件中有以下數據:
5*0 4 3 2 5 7 7 3 6 3 2 6
8*2 4 5 6 7 8 7 3 7 7 3
我想在 python 中處理數據。 所以,我猜最好將它轉換為字符串或列表。
我使用了以下代碼:
a = open('test.txt', 'r')
b = a.readlines()
c = [x.replace('\n','') for x in b]
print(c)
但它給出了:
['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3']
我想知道如何將其轉換為以下內容:
['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']
我會簡單地通過read
方法更改readlines
(不會將行拆分為不同的列表項),然后用空格更改'\\n'
換行符,最后用空格拆分字符串。
a = open('test.txt', 'r')
b = a.read()
c = b.replace('\n', ' ').strip().split(' ')
a.close()
print(c)
我建議使用with
語句以免忘記關閉文件
with open('test.txt', 'r') as a:
b = a.read()
c = b.replace('\n', ' ').strip().split(' ')
print(c)
嘗試這個
a = open('test.txt', 'r')
b = a.readlines()
new_list = []
for line in b:
for item in line.strip().split():
new_list.append(item)
print(new_list)
我會將其轉換為列表壓縮並編輯帖子,但這里沒有
a = open('test.txt', 'r')
b = a.readlines()
c = [a for n in str(b).split('\n') for a in n.split(' ') if a != '']
print(c)
>>> ['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']
你可以這樣做
c=['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3']
c=[j for i in c for j in i.split()]
print(c)
輸出
['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']
with open('test.txt') as file:
print(file.read().split())
我使用with
方法打開和讀取文件以及.read()
方法,該方法讀取整個文件而不是一次一行,然后.split()
方法在每個' '
處拆分字符串,返回一個列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.