gpt4 book ai didi

python: 'str' 对象没有属性 'iteritems'

转载 作者:行者123 更新时间:2023-11-28 21:23:48 29 4
gpt4 key购买 nike

我想使用 python 进行大量查找和替换。

tot11.txt 是一个字符串(有 600000 个项目),我想从文件 1.txt 中替换这里的项目。

例如 tot11.txt 有:

'alba', 'raim',

1.txt 看起来像这样:

'alba':'barba', 'raim':'uva'.

因此我会得到 'barba''uva' 等等...

当我运行脚本时,出现以下错误:

Traceback (most recent call last):
File "sort2.py", line 12, in <module>
txt = replace_all(my_text, dic)
File "sort2.py", line 4, in replace_all
for i, j in dic.iteritems():
AttributeError: 'str' object has no attribute 'iteritems'

如果我不使用文本文件,脚本也能很好地工作,只是在脚本中编写可更改的项目。

import sys

def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text

my_text= open('tot11.txt', 'r').read()

reps = open('1.txt', 'r').read()

txt = replace_all(my_text, reps)

f = open('results.txt', 'w')
sys.stdout = f
print txt

最佳答案

open('1.txt', 'r').read() 返回一个字符串而不是字典。

>>> print file.read.__doc__
read([size]) -> read at most size bytes, returned as a string.

如果 1.txt 包含:

'alba':'barba', 'raim':'uva'

然后你可以使用 ast.literal_eval 来获取字典:

>>> from ast import literal_eval
>>> with open("1.txt") as f:
dic = literal_eval('{' + f.read() +'}')
print dic
...
{'alba': 'barba', 'raim': 'uva'}

您应该使用 regex 而不是 str.replace,因为 str.replace('alba','barba') 将还可以替换 'albaa''balba' 等词:

import re
def replace_all(text, dic):
for i, j in dic.iteritems():
text = re.sub(r"'{}'".format(i), "'{}'".format(j), text)
return text

关于python: 'str' 对象没有属性 'iteritems',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16897122/

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