Python 为什么我的代码打印的是同一个姓?

Python 为什么我的代码打印的是同一个姓?,python,Python,下面我编写的代码从包含名字和姓氏的示例文件中获取输入。然后它将这些名称转换为示例电子邮件。出于某种原因,脚本不断重复打印相同的姓氏 names.txt如下所示: 姓 代码: import os, re, time, getpass, linecache Original = os.path.join(os.path.expanduser('~'), 'Desktop','namess.txt') File = os.path.join(os.path.expanduser('~'), 'Des

下面我编写的代码从包含名字和姓氏的示例文件中获取输入。然后它将这些名称转换为示例电子邮件。出于某种原因,脚本不断重复打印相同的姓氏

names.txt如下所示: 姓

代码:

import os, re, time, getpass, linecache

Original = os.path.join(os.path.expanduser('~'), 'Desktop','namess.txt')
File = os.path.join(os.path.expanduser('~'), 'Desktop','output.txt')
badNames = []
Names = []

def RemCommas():
    outfile = open(os.path.join('C:\\', 'Users', getpass.getuser(), 'Desktop','output.txt'),'w')
    Filedata = open(Original).read()
    outfile.write(re.sub(',', ' ', Filedata))
    outfile.close()

def ClassNum():
    count = 6
    Year = int(time.strftime('%Y'))
    Class = str((Year - 2013) + 6)
    return Class

def ReadStoreFile():
    i = 0
    OpenFile = open(File) 
    LenFile = len(OpenFile.readlines())
    while i < LenFile:
        i += 1
        badNames.append(linecache.getline(File, i))

def CleanNames():
    i = 0
    while i < len(badNames):
        cleaned = badNames[i].rstrip()
        Names.append(cleaned)
        i += 1

def NamePrint():
    Interns = 'makchessclub.org'
    arrayname = []
    i = 0
    j = 0
    m = 0

    while m < len(Names): 
        Name = Names[m]
        Name = Name.lower()
        InternName = Name[0] + Name[1]
        #------------Checking for space and first name--
        while i < len(Name):
            if Name[i] == ' ':
                i = Name.index(' ')
                break;   
            i += 1
        #---------------adding last name in an array----
        Namelen = len(Name) - (i+1)
        while j < Namelen:
            arrayname.append(Name[i+1])
            j += 1
            i += 1
        #---------------Final Name Print----------------
        Lastname = ''.join(arrayname)
        #print arrayname
        #Lastname = Lastname.strip(' ')
        #print InternName + Lastname + ClassNum() + Interns
        file = open('C:\\Users\\username\\Desktop\\emails.txt', 'a')
        file.write(InternName + Lastname + ClassNum() + Interns + '\n')
        file.close()
        m += 1

RemCommas()
ReadStoreFile()
CleanNames()
NamePrint()

print ''
os.system('pause')    
导入操作系统、re、时间、getpass、linecache
Original=os.path.join(os.path.expanduser(“~”),“Desktop”,“names.txt”)
File=os.path.join(os.path.expanduser(“~”)、“Desktop”和“output.txt”)
坏名字=[]
名称=[]
def RemCommas():
outfile=open(os.path.join('C:\\','Users',getpass.getuser(),'Desktop','output.txt'),'w'))
Filedata=open(原始).read()
outfile.write(re.sub(',','',Filedata))
outfile.close()
def ClassNum():
计数=6
年份=int(time.strftime(“%Y”))
等级=str((2013年)+6)
返回舱
def ReadStoreFile():
i=0
OpenFile=open(文件)
LenFile=len(OpenFile.readlines())
当我打开文件时:
i+=1
append(linecache.getline(文件,i))
def CleanNames():
i=0
而我(坏名字):
cleaned=badNames[i].rstrip()
name.append(已清理)
i+=1
def NamePrint():
实习生='makchessclub.org'
arrayname=[]
i=0
j=0
m=0
而m
姓氏没有更改的原因是您没有在循环中重置
arrayname
。您不断向其添加名称,程序会选择第一个名称。所以你应该把你的
arrayname=[]
放在
后面,而m

我想这就是你想要做的:

import os
import re
import time

def create_mails(input_path, output_path, year, addr):
    with open(input_path, 'r') as data:
        mail = re.sub(r'(\w+)\s*,\s*(\w+)\n?', r'\1\g<2>%s%s\n' % (year, addr), data.read())
    with open(output_path, 'w') as output:
        output.write(mail.lower())
    print 'Mail addresses generated and saved to', output_path
如果
names.txt
是这样的:

First, Last
John,Doe
Spam, Ham
Cabbage, egg
firstlast6@makchessclub.org
johndoe6@makchessclub.org
spamham6@makchessclub.org
cabbageegg6@makchessclub.org
然后
output.txt
将如下所示:

First, Last
John,Doe
Spam, Ham
Cabbage, egg
firstlast6@makchessclub.org
johndoe6@makchessclub.org
spamham6@makchessclub.org
cabbageegg6@makchessclub.org

建议:不要使用
os.path.join('C:\\','Users',getpass.getuser(),'Desktop','something.txt')
,而是使用
os.path.join(os.path.expanduser('~'),'Desktop','something.txt')
。然后,只要用户的主目录中有一个
Desktop
文件夹,它就可以在Windows以外的系统上工作。您不需要在python中迭代字符串,因为您需要的大多数工具都已经提供了。要获取“姓氏”:
name[name.find(“”)+1:
@mbrach:在Python 2中,
print
是一条语句。在Python 3中,
print
是一个函数。因此,该程序在Python 2中是有效的。@icktoofay,谢谢!我不知道。对Ahmed,我向你道歉,+1是因为你需要在找到的空格(“”)后再加一个字符才能找到名字。查找找到了空格,然后+1会带你到第一个非空格。嗯,这适用于名字,其他人甚至不会打印姓氏。arrayname最后是空的。这个答案与这个代码一起工作,但向Sanjay Manohar大声呼喊,他的代码:name[name.find(“”)+1:]使我的代码更有效,并且工作正常。是的,抱歉,Ahmed,接得好。我对arrayname的评论实际上更旨在表明它在整个循环中只设置了一次。很抱歉,我没有考虑到最好的地方是什么。彼得给出了一个更完整、更有效的算法。我的目标主要是回答您的直接问题,即根据您当前的实现,为什么名称没有正确地显示出来。mbratch我比我更欣赏我们的答案,因为它旨在解决我的代码,而不是重新排列它。谢谢男人:)@Ahmed如果你觉得ot有用,请投赞成票!(不管怎么说:没那么难,试着一步一步地理解!)