我從文件中讀取字符喜歡的方式是通過使用列表理解像這樣:
f=open(textfile, 'r')
while 1:
line=f.readline().strip() #this gets rid of the newline character
if line=='':# if there are no more lines, quit looping
f.close()
break
characters=[line[i] for i in range(len(line))] this splits up every character of the line into its own item in a list. NOTE THIS WILL INCLUDE SPACES AND PUNCTUATION
至於使用這些字符作爲變量名,我想你可能想嘗試的字典。對於每次從文件中讀取字符,分配一個值作爲密鑰在這樣
tempdict=dict()
f=open(textfile, 'r')
while 1:
x=f.readline().strip()
if x=='':
f.close()
break
x=[x[i] for i in range(len(x))]
for node in x:
tempdict[node]=''
字典,現在你可以通過調用
tempdict[charactername]
,要麼分配調用這些字符中的每一個值或檢索值。
UPDATE
characterslist=[]
f=open('putyourtextfilenamehere','r')
while 1:
x=f.readline().strip()
if x=='':
f.close()
break
x=[x[i] for i in range(len(x))]
for j in x:
characterslist.append(j)
應閱讀每一行和字符保存到一個名爲characterslist
您可能需要使用數組列表。 – devnull
@devnull不幸的是,我想要做的不能使用數組,我需要有不同的變量。 – darkhoard