2016-11-15 144 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()]) 
相关问题