【问题标题】:Creating a parallel corpus from list of words and list of sentences (Python)从单词列表和句子列表创建并行语料库(Python)
【发布时间】:2021-02-10 04:31:51
【问题描述】:

我正在尝试为监督机器学习创建一个并行语料库。

基本上我想要两个文件,一个每行包含一个完整的句子,另一个仅包含与同一行上的句子相对应的特定手动提取的术语。

我已经创建了每行一个句子的文件;现在我想用每行中的术语生成标签文件。为了说明,这是我想出的代码:

import re

list_of_terms = ["cake", "cola", "water", "stop"]
sentences = ["Let's eat some cake.", "I'd like to have some cola to go with the cake.", "stop eating all this cake, you waterstopper", "I will never eat this again", "cake and cola and water"]
para = []
for line in sentences:
    s = re.findall(r"(?=\b("+'|'.join(list_of_terms)+r")\b)", line)
    para.append(s)
print(*para, sep = "\n")

这会产生我想要的输出:

['cake']
['cola', 'cake']
['stop', 'cake']
[]
['cake', 'cola', 'water']

不幸的是,对于我正在处理的语料库,该代码不能很好地工作。事实上,我面临着 3 种不同的异常。

  1. 对于一个语料库,re.findall 函数始终为每个术语输出和附加 ''。

[('criminal', ''), ('liability', ''), ('legal', ''), ('fiscal', ''), ('criminal', ''), ('law', '')]

感谢此线程中的最后一条评论,我解决了这个问题:Use of findall and parenthesis in Python

[x if x!='' else y for x,y in re.findall(r"(?=\b("+'|'.join(list_of_terms)+r")\b)]

  1. 但是,此方法会引发 ValueError,因为正则表达式没有为我正在使用的另外两个语料库创建“”。对于那些我只是使用 try except - 块并运行示例代码并获得满意的结果。但是为什么在这种情况下正则表达式不创建''?

  2. 最后,另一个 corpra 引发了一个 re.error “re.error: nothing to repeat at position 4950”,我还没有找到解决这个问题的方法。我怀疑“list_of_terms”中有特殊字符;有什么办法可以事先过滤吗?

不用说,我对编码还是很陌生,因为我的背景是翻译而不是计算机科学。所以一个优雅的答案将不胜感激! :)

P.S.:我使用的语料库都在 ACTER Corpus-Collection 中:https://github.com/AylaRT/ACTER

【问题讨论】:

  • 试试re.findall(r"(?=(?<!\w)("+'|'.join(map(re.escape, list_of_terms))+r")(?!\w))", line)
  • 是的!这正是我一直在寻找的。感谢您的直截了当的回答。不过,我真的需要了解那些正则表达式特殊字符。如果您有时间,请详细说明 r"(?=(?

标签: python regex nlp re


【解决方案1】:

您需要re.escapelist_of_terms 列表中的每个项目,并使用明确的单词边界:

re.findall(r"(?=(?<!\w)("+'|'.join(map(re.escape, list_of_terms))+r")(?!\w))", line)

(?&lt;!\w) 否定后向查找匹配前面没有紧跟单词字符(数字、字母或 _)的位置。

(?!\w) 否定前瞻匹配未紧跟字符字符的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多