gpt4 book ai didi

python - pickle 没有以正确的方式工作

转载 作者:行者123 更新时间:2023-12-01 02:24:35 28 4
gpt4 key购买 nike

import nltk
import pickle

input_file=open('file.txt', 'r')
input_datafile=open('newskills1.txt', 'r')

string=input_file.read()
fp=(input_datafile.read().splitlines())

def extract_skills(string):
skills=pickle.load(fp)
skill_set=[]
for skill in skills:
skill= ''+skill+''
if skill.lower() in string:
skill_set.append(skill)
return skill_set

if __name__ == '__main__':
skills= extract_skills(string)
print(skills)

我想从文件中打印技能,但是,这里pickle不起作用。
它显示错误:

_pickle.UnpicklingError: the STRING opcode argument must be quoted

最佳答案

包含 pickle 数据的文件必须作为二进制文件进行写入和读取。请参阅the documentation例如。

您的提取函数应如下所示:

def extract_skills(path):
with open(path, 'rb') as inputFile:
skills = pickle.load(inputFile)

当然,您需要将数据转储到以二进制方式打开的文件中:

def save_skills(path, skills):
with open(path, 'wb') as outputFile:
pickle.dump(outputFile, skills)

此外,你的 main 逻辑似乎有点缺陷。虽然 if __name__ == '__main__' 后面的代码仅在脚本作为主模块运行时执行,但 不在 main 中的代码只能是静态的,即定义。基本上,您的脚本不应该任何事情,除非作为 main 运行。这是一个更干净的版本。

import pickle

def extract_skills(path):
...

def save_skills(path, skills):
...

if __name__ == '__main__':
inputPath = "skills_input.pickle"
outputPath = "skills_output.pickle"

skills = extract_skills(inputPath)
# Modify skills
save_skills(outputPath, skills)

关于python - pickle 没有以正确的方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47531812/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com