gpt4 book ai didi

python - 没有分隔符时以某种方式分割行的问题

转载 作者:行者123 更新时间:2023-12-01 08:15:12 25 4
gpt4 key购买 nike

我有一个文本文件;

... Above in Table 5 , we understood the relationship between pressure and volume. It said ... and now we know ... . Table 9: represents the graph of x and y. Table 6 was all about force and it implications on objects....

现在我已经编写了一段代码来提取其中包含单词表的行;

with open file( <pathname + filename.txt>, 'r+') as f:
k = f.readlines()
for line in k:
if ' Table ' in line:
print(line)

现在我希望以特定格式打印输出;

(txt file name),(Table id),(Table content)

我通过使用python的.split方法来做到这一点;

x = 'Paper ID:' + filename.split('.')[0] + '|' + 'Table ID:' + line.split(':')[0] + '|' + 'Table Content:' + line.split(':')[1] + '|' 

现在,正如您所看到的,我可以将表 ID 和表内容分开,其中一些后面有一个分隔符 (:)。如何在没有分隔符的情况下执行相同的操作,即这些行;

Above in Table 5 , we understood the relationship between pressure and volume. It said ... and now we know .. Or In table 7 we saw....

<强>?

有人可以帮忙吗?

最佳答案

您可以搜索模式Table <number>然后在该位置拆分。
您可以使用re.split(pattern, string, maxsplit=0, flags=0)re.findall(pattern, string, flags=0)

re.split('Table [0-9]', line)[-1]

将为您提供以下内容(内容)。

re.findall('Table [0-9]', line)

将为您提供带有 ID 的表,您可以从中提取它。

关于 re.split 的 Python 文档和 re.findall

关于python - 没有分隔符时以某种方式分割行的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55030560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com