[英]Coverting strings from a text file to integers
[0, 1, 2, 3],[4, 5, 6, 7, 8],[9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23]
[0, 1, 2],[3, 4, 5],[6, 7, 8, 9],[10, 11, 12, 13]
[0, 1],[2],[3, 4, 5],[6, 7, 8, 9]
[0, 1, 2, 3],[4, 5, 6, 7],[8],[9, 10, 11, 12],[13, 14, 15]
我有上面的文本文件。 問題是該文件中的每個索引都是一個字符串,但是我想將它們轉換回整數。 我嘗試了這個:
with open("abc.txt", "r") as text_file:
new_list = [int(line) for line in text_file]
我收到此錯誤:
ValueError: invalid literal for int() with base 10: '[0, 1, 2, 3],[4, 5, 6, 7, 8],[9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23]\n'
輸出 -
[0, 1, 2, 3],[4, 5, 6, 7, 8],[9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23]
[0, 1, 2],[3, 4, 5],[6, 7, 8, 9],[10, 11, 12, 13]
[0, 1],[2],[3, 4, 5],[6, 7, 8, 9]
[0, 1, 2, 3],[4, 5, 6, 7],[8],[9, 10, 11, 12],[13, 14, 15]
只是所有這些行都代表包含INTEGERS的列表。
嘗試這個,
import ast
with open("abc.txt", "r") as text_file:
new_list = [list(ast.literal_eval(line)) for line in text_file if line.strip()]
輸出:
[[[0, 1, 2, 3], [4, 5, 6, 7, 8], [9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23]],
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9], [10, 11, 12, 13]],
[[0, 1], [2], [3, 4, 5], [6, 7, 8, 9]],
[[0, 1, 2, 3], [4, 5, 6, 7], [8], [9, 10, 11, 12], [13, 14, 15]]]
您可以使用literal_eval
和chain
:
from ast import literal_eval
from itertools import chain
with open("abc.txt", "r") as text_file:
new_lines = (list(literal_eval(line)) for line in text_file if line.strip())
new_list = list(chain(*new_lines))
line.strip()
將跳過空行。
讀完這樣的數據后,正則表達式是最好的選擇,
z = re.findall("[\d]+",your_string)
然后剩下的就是將列表中的每個字符串轉換為整數,這是一個簡單的示例,
for i in range(len(z)):
new_z[i] = int(z[i])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.