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

时间:2011-03-28 17:23:34

标签: python regex

我正在尝试从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)\|" 

那么诗集的正则表达式应该由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")

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

我认为最简单的方法是使用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]

答案 2 :(得分:-1)

用括号括起来?这不是所有正则表达式的工作原理吗?