2013-06-03 174 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))