首页 > 解决方案 > 为特定上下文设置字符串变量

问题描述

import gzip
with gzip.open('File_name', 'rb')as f:

for line in f:
    line.decode("utf-8") #Is this how I transfer bytes to string in this context ?

print(line)


doc = nlp(line)* #If I define "line", it would give an output of the entire text instead of below"

print("Abbreviation", "\t", "Definition")

for abrv in doc._.abbreviations:
print(f"{abrv} \t ({abrv.start}, {abrv.end}) {abrv._.long_form}")

如何将字符串变量设置为“line”,以便将其输入到 nlp 函数中?我尝试为它设置一个定义,但它会打印出整个文本而不是运行缩写输出。

标签: pythonnlpspacy

解决方案


该代码有点难以阅读,因为缩进不匹配。但是你可以试试:

line = line.decode("utf-8")

在 Python 中,字符串是不可变的,因此无论何时对字符串执行函数,都需要将结果捕获到变量中,无论是新的 var 还是现有的 var。


推荐阅读