好吧,我正在做一个程序,它可以做一系列的事情。它首先读取2个外部文件的内容,然后将所述文件的每一行转换成一个列表,然后将这两个列表合并成一个列表。在
每个文件都是一个名称列表,前面有一个条目号,后面有一个新行。因此,每个文件都是100到200个条目的列表,格式如下:1. Michael \n
2. Ben \n
3. Ken \n
4. David \n
所以程序打开文件,然后把每一行读到一个列表中。在
这就是我的问题所在。我需要从每一行中去掉条目号、空白和换行命令。在
我在用阿琳·阿普利特('')对于每一行,以便:
^{pr2}$
会变成:
['1','Michael\n']
好的,从这里开始,我只需要去掉'\n',然后将[1]附加到这个文件的名称列表中。在
好吧,这就是我出错的地方。具体来说:Traceback (most recent call last):
File "H:/ITP100/assignments/Chapter 7/Names-3.py", line 30, in
entry1 = value_xy.rstrip('\n')
AttributeError: 'list' object has no attribute 'rstrip'
以下是完整代码:Name1 = (input("Enter a name: "))
file_xy = open("BoyNames.txt", "r")
list_xy = []
file_xx = open("GirlNames.txt", "r")
list_xx = []
test_boys =[]
test_girls =[]
entry1 = []
for aline in file_xy:
value_xy = aline.split(' ')
entry1 = value_xy.rstrip('\n')
test_boys.append[1]
#entry2 = entry1[1].strip()
list_xy.append(entry1[1])
for aline in file_xx:
value_xx = aline.split(' ')
entry_xx1 = value_xx.rstrip('\n')
test_girls.append(entry_xx1)
# entry_xx2 = value_xx[1].lstrip()
list_xx.append(entry_xx1)
#print(list_xy)
names = list_xy + list_xx
print("This is the list \'names\'. This is the combined list of all names."+'\n'+str(names))
print("This is the list \'test_boys\'. This is the post-stripping list of boy names."+'\n'+str(test_boys))
print("This is the list \'test_girls\'. This is the post-stripping list of girl names."+'\n'+str(test_girls))
if Name1 in names:
print(Name1+" is in the list.")
else:
print(Name1+" is not in the list.")