python:“str”对象没有“iteritems”属性

2024-06-17 13:13:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: textintxt脚本myopenallreplace
3条回答

replace_all函数的第二个参数是一个字符串,它来自reps=open('1.txt','r').read()。。。。因此,对字符串对象调用iteritems()失败,因为该函数对于字符串对象不存在。

open('1.txt', 'r').read()返回的字符串不是dict

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

如果1.txt包含:

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

然后可以使用ast.literal_eval获取dict:

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

与其使用str.replace,不如使用regex,因为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

你不需要用字面上的评价。 这是你的档案:

% cat 1.txt 
foo:bar
abc:def

这是读入字典的代码。正如Ashwini Chaudhary所说,您得到这个错误是因为读取read()返回一个字符串。字符串没有名为iteritems的方法。

>>> dic = {}
>>> with open('1.txt') as f:
...     for line in f:
...             trimmed_line = line.strip()
...             if trimmed_line:
...                     (key, value) = trimmed_line.split(':')
...                     dic[key]=value
... 
>>> dic
{'foo': 'bar', 'abc': 'def'}

当然,这假设您的文件中每行只有1:

相关问题 更多 >