【发布时间】:2018-05-08 17:54:36
【问题描述】:
我有一个包含数千行字符串的 txt 文件。 每行以“#integer”的格式开始,例如“#100”。
我按顺序读取 txt 文件(第 1 行、第 2 行、第 3 行……)并得到一个我想要的特定数组,其中该数组是行号和连接到这些行的其他行的集合:
数组的形式为:
[ ['#355', '#354', '#357', '#356'], ['#10043', '#10047', '#10045'], ['#1221', '#1220', '#1223', '#1222', '#1224'], [...] ]
它可以包含数百个数字。 (这是因为我有一个数字数组以及与它们相关的更多“孩子”添加到每个子数组中。)
我在下面的函数之前读取了我的 txt 文件,这意味着我首先读取了我的 txt 文件,提取数字,然后将其作为数组传递给 extended_Strings 函数,该函数将每个数字替换为txt 文件中该数字行的实际字符串。
def extended_strings(matrix,base_txt):
string_matrix = matrix #new matrix to contain our future strings
for numset in string_matrix:
for num in numset:
for line in base_txt:
results = re.findall(r'^#\d+', line) #find the line # at start of string
if len(results) > 0 and results[0] == num: #if we have a # line that matches our # in the numset
index = numset.index(num) #find index of line # in the numset
numset[index] = line #if we match line #'s, we replace the line # with the actual string from the txt
return string_matrix
我正在努力让这个过程更短更高效,例如我在 txt 中有 150,000 个字符串,使用for line in base_txt 行扫描 txt 文件有数百万次。
有什么建议吗?
【问题讨论】:
-
您能详细说明您的帖子吗?文本文件中的每一行是否以数字(整数)开头?如果是这样,这些行是否按这些数字排序?在使用“extended_strings”函数之前,您是否阅读过文本文件?请举例说明您的矩阵“[[[],[],...],[[],[],...],[[],[],...]...](级别1)"。据我了解,这是一个“numsets”列表(2 级)。下一个内部列表“num”(第 3 级)看起来像 nums 列表。另一方面,您的函数似乎将“num”作为单个数字处理,而不是作为列表处理。
-
Werner Wenzel - 我已经编辑了我的帖子以匹配您的问题。谢谢。
标签: python arrays string nested text-files