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

标签 python string

我想使用 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/

相关文章:

Python,无法打开文本文件

python - 在Python中绘制Z平面上的复数列表

c# - StringBuilder 真的比 Aggregate 快吗?

php - 在 PHP 中测试 UTF-8 字符串是一种可靠的方法吗?

php - 标记段落中的短语

java - 正则表达式程序

python - 促进代码生成的最佳 Python 模板库

python - 如何安装 python 的覆盖模块并在 Windows 中从命令行使用它

python - 调整 matplotlib 注释框内的填充

java - 反转字符串数组中的字符