python - 尝试对文本进行词形还原时出现断言错误(python、StanfordNLP)
问题描述
我想在数据框的一列中对文本进行词形还原。我的脚本似乎适用于一个简短的测试数据框,但每次我尝试在我的实际项目文件上运行它时,我都会收到一个断言错误。我认为这可能与文本的长度有关,但不知道如何处理它。
我的代码:
import pandas as pd
import stanfordnlp
nlp = stanfordnlp.Pipeline(lang = "en", processors='tokenize,mwt,pos,lemma')
def lemmatize(text):
'''lemmatize'''
count = 0
fout = open('text_lemmatized.txt', 'w+')
doc = nlp(text)
for sent in doc.sentences:
for word in sent.words:
word = word.lemma
fout.write(str(word))
fout.write(" ")
count = count + 1
fout = open('text_lemmatized.txt', 'r')
text = fout.read()
print(text)
return text
lemmatizing = lambda x: lemmatize(x)
data = pd.read_csv("data.csv")
data_lemma = pd.DataFrame(data.text.apply(lemmatizing))
data_lemma.to_csv("lemma-text-en.csv")
我得到的追溯是:
回溯(最后一次调用):文件“lemmatize.py”,第 28 行,在 data_lemma = pd.DataFrame(data_clean.corpus.apply(lemmatizing)) 文件“/opt/anaconda3/lib/python3.7/site-packages /pandas/core/series.py”,第 4042 行,在 apply mapped = lib.map_infer(values, f, convert=convert_dtype) 文件“pandas/_libs/lib.pyx”,第 2228 行,在 pandas._libs.lib 中。 map_infer 文件“lemmatize.py”,第 25 行,在 lemmatizing = lambda x: lemmatize(x) 文件“lemmatize.py”,第 11 行,在 lemmatize doc = nlp(text) 文件“/opt/anaconda3/lib/python3. 7/site-packages/stanfordnlp/pipeline/core.py”,第 176 行,通话中 self.process(doc) 文件“/opt/anaconda3/lib/python3.7/site-packages/stanfordnlp/pipeline/core.py”,第 170 行,正在处理 self.processors[processor_name].process(doc) 文件“ /opt/anaconda3/lib/python3.7/site-packages/stanfordnlp/pipeline/pos_processor.py”,第 31 行,正在处理中的 i、b 枚举(批处理):文件“/opt/anaconda3/lib/python3. 7/site-packages/stanfordnlp/models/pos/data.py”,第 120 行,在iter yield self 中。getitem (i) 文件“/opt/anaconda3/lib/python3.7/site-packages/stanfordnlp/models/pos/data.py”,第 91 行,在getitem assert len(batch) == 6
似乎是什么问题?如果是文本的长度,那么处理它的有效方法是什么?(我在该列中只有两个单元格,但是这两个单元格中有很多文本需要进行词形还原)。
感谢您的任何建议!
解决方案
该错误发生在词性标注器中,预词法化。尝试将pos_batch_size
其作为参数添加到Pipeline
,并为其指定一个等于或大于最长句子的数字。根据这个Github issue,
如果您标记的句子长于
pos_batch_size
,则方法chunk_batches
会创建随后触发断言的空批次:assert len(batch) == 6
如下更新您的代码,其中max_sent_len
比您最长的句子更长:
max_sent_len = 4096
nlp = stanfordnlp.Pipeline(lang="en", processors='tokenize,mwt,pos,lemma', pos_batch_size=max_sent_len)
注意:我也使用 depparse 处理器,并且也必须更新depparse_batch_size
。
推荐阅读
- android - hostpython2 构建错误(对于使用 Kivy 的 Android)
- json - Rswag 模式不会因数组中对象的无效属性而失败
- python - 适当的轮廓中断
- tomcat - 我们可以在tomcat中部署两个同名的war文件吗?
- c# - Asp.net 从数据库生成页面
- python - django 中的 Razorpay 支付按钮连接
- javascript - Javascript点击一个元素显示它,点击另一个:隐藏第一个并显示第二个
- corda - 如何将 UniqueIdentifier 序列化为字符串并返回
- swift - 使用 GCD 在 Swift 中创建串行队列的问题
- python - 关于如何使用 python(在 SOM 上工作)绘制 U-MATRIX 的任何示例/想法?