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

2024-05-17 05:04:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从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

最后两个值是诗句和章节。

这里是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)\|" 

然后,组(1)应获得韵文的regexp

但我不知道如何在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")

Tags: 文件theto字符串inarfffor诗句
3条回答

带圆括号?不是所有的正则表达式都是这样工作的吗?

如果您的所有行的格式都是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]

我认为最简单的方法是使用re.split()来获取经文 还有一个re.findall()来得到章节和诗节的数字 结果将存储在列表中,以后可以使用 下面是一个代码示例:

#!/usr/bin/env python

import re

# string to be parsed
Quran= '''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.'''

# list containing the text of all the verses
verses=re.split(r'[0-9]+\|[0-9]+\|',Quran)
verses.remove("")

# list containing the chapter and verse number:
#
#   if you look closely, the regex should be r'[0-9]+\|[0-9]+\|'
#   i ommited the last pipe character so that later when you need to split
#   the string to get the chapter and verse nembuer you wont have an
#   empty string at the end of the list
#
chapter_verse=re.findall(r'[0-9]+\|[0-9]+',Quran)


# looping over the text of the verses assuming len(verses)==len(chp_vrs)
for index in range(len(verses)):
    chapterNumber,verseNumber =chapter_verse[index].split("|")
    print "Chapter :",chapterNumber, "\tVerse :",verseNumber
    print verses[index]

相关问题 更多 >