I am a very beginning programmer looking for some help with what is probably a very simple problem. I am trying to write a program that will read a .txt file and then replace any words with an 'e' in them with 'xxxxx'.
Here is what I have so far:
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()
Could someone help me with this any give me any critques/pointers?
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)
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
One line for the loops can be written in the form of list comprehension as:
[' '.join([('xxxx' if 'e' in word else word) for word in line]) for line in file.readlines()]
一线
print "\n".join([" ".join([[word, "xxx"]["e" in word] for word in line.split()]) for line in open("file").readlines()])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.