我是一个非常初期的程序员,正在寻找一些可能是一个非常简单的问题的帮助。我正在尝试编写一个程序来读取.txt文件,然后用'xxxxx'替换任何带有'e'的单词。
这是我到目前为止所做的:
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()
有人可以帮我解决这个问题吗?
答案 0 :(得分: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)
答案 1 :(得分: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()]
答案 2 :(得分:0)
一个班轮:
print "\n".join([" ".join([[word, "xxx"]["e" in word] for word in line.split()]) for line in open("file").readlines()])