【发布时间】:2020-01-17 08:09:13
【问题描述】:
Python 代码在名字、姓氏和电子邮件地址之间输出一个新行,我怎样才能阻止这种情况发生?例如
ogchu
@gmail.com
ogchu
@yahoo.com
ogchu
@hotmail.com
ogchu
@aol.com
ogchu
@bigpond.com
first.txt 和 last.txt 文件分别有大约 2,000 个和 100 个名称,因此手动浏览并做一些事情并不是一个真正的选择。
代码的目的是尝试生成看起来真实的电子邮件地址,有时包含名字和姓氏,有时包含 1 个首字母和一个姓氏,有时包含 2 个首字母和一个姓氏。
代码:
import random
import string
import time
count = 0
while count < 50:
x = random.randint(0, 1)
y = random.randint(0, 1)
z = random.randint(0, 1)
if x == 0:
prefix1 = random.choice(string.ascii_lowercase)
prefix2 = random.choice(string.ascii_lowercase)
first = ""
if x == 1:
prefix1 = random.choice(string.ascii_lowercase)
prefix2 = ""
first = ""
if x == 1 and y == 1:
prefix1 = ""
prefix2 = ""
first = random.choice(open('first.txt').readlines())
last = random.choice(open('last.txt').readlines())
print(prefix1 + prefix2 + first + last + "@gmail.com")
print(prefix1 + prefix2 + first + last + "@yahoo.com")
print(prefix1 + prefix2 + first + last + "@hotmail.com")
print(prefix1 + prefix2 + first + last + "@aol.com")
print(prefix1 + prefix2 + first + last + "@bigpond.com")
print(prefix1 + prefix2 + first + last + "@icloud.com")
print(prefix1 + prefix2 + first + last + "@outlook.com")
count = count + 1
time.sleep(3)
【问题讨论】:
-
... + last.strip() + ...?您正在从文件中读取这些名称,这些行后面有换行符。 -
@jonrsharpe 所以我需要从两个文件的每一行中删除换行符吗?我可以写一个程序来帮我做吗?
-
@jonrsharpe:我已经重新打开了它(甚至在阅读您的评论之前:-))
-
如果您从文件中删除了换行符,这有什么帮助?是的,可以编写一个程序来做到这一点,但是你会读到一行,所有的名字都混在一起了。只需按照我上面的建议进行操作,使用 strip 方法从所选值中删除换行符。