<p>我试图从python中的字符串中提取子字符串。</p>
<p>我的数据文件包含古兰经中的每一行,每一行在字符串的开头都标有诗句和章节号。
我想尝试提取第一个数字和第二个数字,并将它们写入另一个文本文件中的一行
以下是txt文件的几行示例。</p>
<pre><code>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.
</code></pre>
<p>如您所见,诗句和章节可能包含多个数字,因此仅从字符串开始计算空格数是不够的。
有没有一种方法可以使用正则表达式尝试将第一个数字(韵文)和第二个数字(章节)提取为字符串?</p>
<p>我写这篇文章的代码将尝试将诗句和章节字符串写入Arff文件。
arff文件中的一行示例如下:</p>
<pre><code>1,0,0,0,0,0,0,0,0,2,12
</code></pre>
<p>最后两个值是诗句和章节。</p>
<p>这里是for循环,它将为每一个诗句编写我感兴趣的属性,然后我想尝试通过使用正则表达式为每一行提取相关的子字符串来将诗句和章节写到最后。</p>
<pre><code>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")
</code></pre>
<p>我认为章节号(管道前的第一个数字)的正则表达式应该是这样的,然后使用group(0)函数来获取第一个数字</p>
<pre><code>"^(\d+)\|(\d)\|"
</code></pre>
<p>然后,组(1)应获得韵文的regexp</p>
<p>但我不知道如何在python中实现这一点。
有人有什么想法吗?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
对问题的回答。</p>
<p>我刚刚试图实现你的技术,但得到一个“索引错误:列表索引超出范围。我的代码是</p>
<pre><code>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")
</code></pre>