[英]Reading a text file line by line and converting it into a list using only read()?
所以我有一個包含以下數字的 txt 文件:
10
5
6
2
3
4
1
9
34
22
5
每行只有一個數字。 我想將所有數字放在一個列表中,並且只使用read()
function。 不允許使用readline()
或readlines()
。
這就是我嘗試做的(注意我必須像這樣使用 function):
def get_list1(text):
result=[]
for row in text:
result.append(row)
return result
with open("file.txt") as f:
n = f.read()
l=get_list1(n)
print(l)
這是 output:
['1', '0', '\n', '5', '\n', '6', '\n', '2', '\n', '3', '\n', '4', '\n', '1',
'\n', '9', '\n', '3', '4', '\n', '2', '2', '\n', '5']
如您所見,它包含\n
並將數字拆分為其數字。
我想要一個 output
['10','5','6','2','3','4','1','9','34','22','5']
您可以使用split()
:
def get_list1(text):
result=[]
for row in text:
result.append(row)
return result
with open("test.txt") as f:
n = f.read().split("\n")
l=get_list1(n)
print(l)
或者只使用splitlines()
def get_list1(text):
result=[]
for row in text:
result.append(row)
return result
with open("test.txt") as f:
n = f.read().splitlines()
l=get_list1(n)
print(l)
做到這一點的捷徑是
def get_list1(text):
return text.split("\n")
with open("file.txt") as f:
get_list1(f.read())
或者你可以用類似的東西替換 function
# takes care of empty lines as well and create actual integers in a list
l = list(map(int, (w.strip() for w in f.read().split() if w.strip())))
你的錯誤是因為:
def get_list1(text): # text is a big text with \n in it result=[] # iterates the big blob of text as single characters for row in text: result.append(row) return result
如果你不能使用任何split()
你可以一次解析你的文件一個字符:
def get_list1(text):
"""This function takes a text with included newlines \n, and processes it
characterwise. Each character is added into a list of lists where the last
of it is always a list. A character is added to that last inner list
if it is not a \n.
If a \n is encountered, the last inner list is converted to a string
(if not empty - to account for newlines in the input) and a new empty
list is added for the characters of the next line. At the end the case
of last character == \n is handled. A list of line texts is returned."""
result=[[]]
for character in text:
if character == "\n":
t = ''.join(result[-1]).strip()
if len(t) > 0:
# change list of characters into string
result[-1] = int(t)
result.append([])
else:
result[-1].clear()
continue
result[-1].append(character)
try:
t = ''.join(result[-1]).strip()
if len(t) > 0:
# change list of characters into string
result[-1] = int(t)
else:
result = result[:-1]
except:
result = result[:-1]
return result
print(get_list1("1\n11\n111\n111\n11111\n11\n"))
Output:
[1, 11, 111, 111, 11111, 11]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.