python - 如何在 python 中将文本文件分段?

标签 python regex

我有一个文本文件:

000140.psd

1) You've heard of slow food. 

nsubj(heard-3, You-1)
aux(heard-3, 've-2)
root(ROOT-0, heard-3)
case(food-6, of-4)
amod(food-6, slow-5) s1
nmod:of(heard-3, food-6) t1

2) This is slow denim. 

nsubj(denim-4, This-1)
cop(denim-4, is-2)
amod(denim-4, slow-3) s1
root(ROOT-0, denim-4) t1

我想运行一个循环来查看每个段落中包含 s1 (或 s2、s3 等)的所有行。 我希望能够为每个段落创建两个列表。第一个列表将包含其中包含“s#”的行,另一个列表将包含所有行。 这样我就可以创建“规则”来确定哪些行应标记为“t#”,在本例中给出了 t1,但我想在尚未标记的情况下确定 t#。 有没有办法为每个段落制作 2 个不同的列表,以便我可以自动进行比较?

我已经尝试过:

lexxe = open('000140.ant')
for line in lexxe:
    line = line.rstrip()
    if re.search('s[0-9]$', line):
        source.append(line)
print(source)

但这只给了我一个包含 s + 数字的所有行的列表。

最佳答案

您需要首先将文本拆分为段落,然后进行您想要执行的处理:

将文件读入字符串:

lexxe = open('000140.ant').read()

然后使用正则表达式将其分成段落:

paragraphs = re.sub(r'(\n\d\))', r'|\1', lexxe).split('|')

这将在每个新行上分割,后跟一个数字和一个右括号。我必须采取解决方法,使用 | 字符,这样段落的开头就不会被消耗。如果您在文本中的任何位置使用 |,这将不起作用,但您可以选择不同的字符。

您可以使用列表理解按段落找到 s# 行:

source = [[l.rstrip() for l in p.split('\n') if re.search(r's\d$', l.rstrip())] for p in paragraphs]

所以你最终会得到:

> paragraphs
['\n000140.psd\n', "\n1) You've heard of slow food. \n\nnsubj(heard-3, You-1)\naux(heard-3, 've-2)\nroot(ROOT-0, heard-3)\ncase(food-6, of-4)\namod(food-6, slow-5) s1\nnmod:of(heard-3, food-6) t1\n", '\n2) This is slow denim. \n\nnsubj(denim-4, This-1)\ncop(denim-4, is-2)\namod(denim-4, slow-3) s1\nroot(ROOT-0, denim-4) t1\n']

您可以将其分成几行:

paragraph_lines = [p.split('\n') for p in paragraphs]

给你:

> paragraph_lines
[['', '000140.psd', ''], ['', "1) You've heard of slow food. ", '', 'nsubj(heard-3, You-1)', "aux(heard-3, 've-2)", 'root(ROOT-0, heard-3)', 'case(food-6, of-4)', 'amod(food-6, slow-5) s1', 'nmod:of(heard-3, food-6) t1', ''], ['', '2) This is slow denim. ', '', 'nsubj(denim-4, This-1)', 'cop(denim-4, is-2)', 'amod(denim-4, slow-3) s1', 'root(ROOT-0, denim-4) t1', '']]

并且将是:

> source
[[], ['amod(food-6, slow-5) s1'], ['amod(denim-4, slow-3) s1']]

请记住,您将把标题 (000140.psd) 作为段落,但您只需执行 paragraphs = paragraphs[1:] 即可获得摆脱它

关于python - 如何在 python 中将文本文件分段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57962716/

相关文章:

python - 如何获取 python 数组中的所有 "ids"

python - 将随机数量的随机数写入文件并返回它们的平方

Java Regex - 非零正整数的字符串表示

c++ - 使用 QString 替换方法用正则表达式更改文件名

javascript - 修复 json.parse 正则表达式与 "$"字符冲突中的 JQuery-1.4.1 和 json-2.0 冲突

python - 查找子字符串在字符串中存在的次数 - Python

python - 使用外部定义的函数修改模块全局变量

python - deeplab在自己的数据集上训练时从检查点恢复失败

regex - Sublime 的 : replace everything between quotes

regex - 检查字符串是否以 OCaml 中的某些文本结尾的最方便方法?