2013-06-03 115 views
1

我想用python做一个巨大的查找和替换。python:'str'对象没有属性'iteritems'

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 

回答

5

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'} 

而不是使用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 
+0

非常感谢,现在它工作。 – Viki

+0

@ user2335306很高兴帮助。 –

0

的replace_all函数的第二个参数是一个字符串,因为它从代表=开放( '的1.txt', 'R')来了。读()....所以主叫iteritems()通过字符串对象失败,因为该函数不存在字符串对象。

0

您不需要使用literal_eval。 这里是你的文件:

% 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 :

+0

我们不能做到这一点吗? '''dic = dict(i.strip()。split(':',1)for i in f if i and':'in i)''' – oleg

+0

是的,我想你可以:) – m01

0

首先,你应该得到的替代品了某处文件:

lookup = {} # an empty dictionary 
with open('replacements.txt') as f: 
    for line in f: 
     if ':' in line: 
      bits = line.strip().split(':') 
      lookup[bits[0].strip()] = bits[1].strip() 

接下来,阅读要替换文件:

with open('somefile.txt') as infile, open('results.txt','w') as out: 
    for line in infile: 
     words = line.split() # splits on whitespace 
     for word in words: 
      # For each word, see if it has a replacement 
      # if it does, write the replacement otherwise write the word 
      # to the outfile 
      out.write(lookup.get(word,word))