gpt4 book ai didi

python - 如何在Python中使用正则表达式提取字符串

转载 作者:行者123 更新时间:2023-11-30 23:53:48 25 4
gpt4 key购买 nike

我正在尝试从 python 中的字符串中提取子字符串。

我的数据文件包含古兰经的行,其中每一行在字符串的开头都标有经文和章节号。 我想尝试提取第一个数字和第二个数字并将它们写入另一个文本文件中的一行以下是 txt 文件的几行示例。

2|12|Of a surety, they are the ones who make mischief, but they realise (it) not.
2|242|Thus doth Allah Make clear His Signs to you: In order that ye may understand.

正如您所看到的,诗句和章节可能包含多个数字,因此仅计算从字符串开头开始的空格数是不够的。有没有办法使用正则表达式尝试将第一个数字(诗句)和第二个数字(章节)提取为字符串?

我正在编写的代码将尝试将诗句和章节字符串写入 Arff 文件。arff 文件中的一行示例如下:

1,0,0,0,0,0,0,0,0,2,12

其中最后 2 个值是诗句和章节。

这里是 for 循环,它将为每节经文写入我感兴趣的属性,然后我想尝试通过使用正则表达式提取每行的相关子字符串来将经文和章节写入末尾。

for line in verses:
for item in topten:
count = line.count(item)
ARFF_FILE.write(str(count) + ",")
# Here is where i could use regular expressions to extract the desired substring
# verse and chapter then write these to the end of a line in the arff file.
ARFF_FILE.write("\n")

我认为章节编号(管道之前的第一个数字)的正则表达式应该是这样的,然后使用 group(0) 函数获取第一个数字并

"^(\d+)\|(\d)\|" 

那么 verse 的正则表达式应该由 group(1) 获得

但我不知道如何在 python 中实现它。有人有什么想法吗?~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~回答问题。

我刚刚尝试实现您的技术,但收到“索引错误:列表索引超出范围。我的代码是

for line in verses:
for item in topten:
parts = line.split('|')

count = line.count(item)
ARFF_FILE.write(str(count) + ",")
ARFF_FILE.write(parts[0] + ",")
ARFF_FILE.write(parts[1])
ARFF_FILE.write("\n")

最佳答案

如果所有行的格式都类似于 A|B|C,那么您不需要任何正则表达式,只需将其拆分即可。

for line in fp:
parts = line.split('|') # or line.split('|', 2) if the last part can contain |
# use parts[0], parts[1]

关于python - 如何在Python中使用正则表达式提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5462659/

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