Assume you\'re working on a contract where a company is building a mailing list
ID: 3811902 • Letter: A
Question
Assume you're working on a contract where a company is building a mailing list (or, rather, an e-mailing list) by analyzing e-mail messages. Your task is to write a Python program that reads a file (stored in the current working directory) called mail.dat and outputs to a file called addresses.dat, one per line, every e-mail address contained inside the file. For this assignment, if a whitespace delimited string of characters has an embedded commercial at sign (@) inside it (that is, interior to the string), we shall consider it an e-mail address. However, any trailing commas must be trimmed from addresses. Thus the string "..c@mtsu.edu," must appear in the output file as "..c@mtsu.edu" with the trailing comma removed. Only commas at the end of a string are considered trailing; do not remove non-trailing commas. Do not worry about any other punctuation characters; the only editing your program must do is to remove trailing commas.
What I have so far is the following:
def main():
mail = open('mail.dat','r')
line = mail.realine()
while line != "":
tokens = line.split()
for word in tokens:
print(tokens)
line = mail.readline()
when I run the program I get each word by itself but in a list.
Explanation / Answer
# pastebin link for the code : https://pastebin.com/94zFKcFe
def main():
with open('addresses.dat', 'w') as out:
with open('mail.dat','r') as mail:
for line in mail:
tokens = line.split()
for word in tokens:
if '@' in word:
word = word.rstrip(",")
out.write(word)
out.write(" ")
if __name__ == "__main__":
main()
I used following as mail.dat
mail1@mail1 junk mail1@withtrailingcomma, junk junk junk mail,insidecomma@comma, mail,inside,@nooutside junk
mail1@mail2 junk mail1@withtrailingcomma, junk junk junk mail,insidecomma@comma, mail,inside,@nooutside junk
mail1@mail3 junk mail1@withtrailingcomma, junk junk junk mail,insidecomma@comma, mail,inside,@nooutside junk
mail1@mail4 junk mail1@withtrailingcomma, junk junk junk mail,insidecomma@comma, mail,inside,@nooutside junk
Here is my output
mail1@mail1
mail1@withtrailingcomma
mail,insidecomma@comma
mail,inside,@nooutside
mail1@mail2
mail1@withtrailingcomma
mail,insidecomma@comma
mail,inside,@nooutside
mail1@mail3
mail1@withtrailingcomma
mail,insidecomma@comma
mail,inside,@nooutside
mail1@mail4
mail1@withtrailingcomma
mail,insidecomma@comma
mail,inside,@nooutside
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.