2016-11-15 88 views
0

我是一個非常初級的程序員,他正在尋找一些可能非常簡單的問題的幫助。我正在嘗試編寫一個程序來讀取.txt文件,然後用'xxxxx'替換其中的'e'。用python替換字符串中的單詞

這是我到目前爲止有:

def replace_ewords(text): 
    ntext = text.replace('e', 'xxxxx') 

def main(): 
    filename = "gb.txt" 
    text = readfile(filename) 
    new_text = replace_ewords(text) 
    print(new_text) 

main() 

可能有人能幫我解決這個任何給我任何critques /指針?

+1

首先你的函數'replace_ewords'需要'返回ntext'。 – sal

+1

什麼是「readfile()」功能?.....我相信replace_ewords()函數必須放在一個循環遍歷文件對象的函數中......你能提供更多的代碼嗎? – repzero

+0

您是否試圖用'xxxxx'替換包含'e'的所有單詞?或者你只是用'xxxxx'替換每個單詞中的'e'? – ecounysis

回答

0
def replace_ewords(text): 
    words = [] 
    text = text.split(' ') 
    for word in text: 
     if "e" in text: 
      words.append("x"*len(text)) 
     else: 
      words.append(text) 
    return " ".join(words) 
0
with open('filename') as f: # Better way to open files :) 
    line_list = [] 
    for line in file: # iterate line by line 
     word_list = [] 
     for word in line.split() # split each line into words 
      if 'e' in word: 
       word = 'xxxxx'  # replace content if word has 'e' 
      word_list.append(word) # create new list for the word content in new file 
     line_list.append(' '.join(word_list)) # list of modified line 

# write this content to the file 
的循環

一號線可以寫在列表理解的形式爲:

[' '.join([('xxxx' if 'e' in word else word) for word in line]) for line in file.readlines()] 
0

一個班輪:

print "\n".join([" ".join([[word, "xxx"]["e" in word] for word in line.split()]) for line in open("file").readlines()]) 
相關問題