【问题标题】:pickle is not working in a proper way泡菜工作不正常
【发布时间】:2018-05-11 22:10:49
【问题描述】:
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)

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

_pickle.UnpicklingError: STRING 操作码参数必须被引用

【问题讨论】:

    标签: python parsing web-scraping pickle


    【解决方案1】:

    包含腌制数据的文件必须作为二进制文件写入和读取。有关示例,请参阅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__' 后面的代码仅在脚本作为主模块运行时才会执行,但在主模块中 的代码只能是静态的,即定义。 基本上,您的脚本不应该任何事情,除非作为主脚本运行。 这是一个更干净的版本。

    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)
    

    【讨论】:

    • 感谢您的回答,但它给出了错误:AttributeError: module 'pickle' has no attribute 'dump'
    • @JayPratapPandey 我缺乏信息。 Pickle 确实有一个 dump 属性,不管 Python 的版本是什么。
    • 我可以在pickle中加载txt文件吗?
    • 它给出了错误:UnpicklingError: the STRING opcode argument must bequoted
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2017-05-21
    • 1970-01-01
    相关资源
    最近更新 更多