我编写了以下代码来编写文件,将其转换为整数值,保存该文件然后读取并将其转换回原始字符串。但是,它会输出两次输出。
我的代码是
def write():
sentence=input('What is your Statement?:')
name=input('Name your file:')
sentence=sentence.lower()
words=sentence.split(' ')
file_register=set()
F_output=[]
position=[]
for i in words:
if i not in file_register:
F_output.append(i)
file_register.add(i)
for x in words:
for y in range(len(F_output)):
if x==F_output[y]:
position.append(y)
name+='.txt'
with open(str(name),'w') as f:
f.write(str(len(position)) + '\n')
for c in range(len(position)):
f.write(str(position[c]) + '\n')
f.write(str(len(F_output)) + '\n')
for d in range(len(F_output)):
f.write(str(F_output[d] + '\n'))
f.close
global name
global position
def read1():
savefile=[]
output=('')
with open(name,'r') as file_open:
num=int(file_open.readline())
while num!=0:
a1=file_open.readline()
a1_split=a1.split('\n')
position.append(int(a1_split[0]))
num-=1
file_integer=int(file_open.readline())
while file_integer!=0:
word_s=file_open.readline()
word_split=word_s.split()
savefile.append(word_split)
file_integer-=1
for n in range(len(position)):
a=position[n]
output+=str(savefile[a])+('')
global output
write()
read1()
print('Your file is: '+output)
我试过搜索,但我找不到答案。我对Python很陌生,感谢任何帮助。
答案 0 :(得分:0)
在write()
中,您将position
声明为全局。在read1()
中,您不会将其声明为全局变量,但由于您从未创建本地position
变量,因此它是使用过的全局变量。因此,您最终会填充两次:一次在write()
,然后再次在read1()
。
简而言之:不要使用全局变量。你不需要它们。
此外,您发现您的代码方式更容易阅读,理解和调试1 /使用更好的命名,2 /编写简单,简单的函数做单一事情,处理他们的输入(参数)和返回值(相同的参数应该产生相同的输出值),3 /正确使用python' s for
循环。
以下是您的代码遵循这些规则的示例:
def parse(sentence):
sentence=sentence.lower()
words=sentence.split(' ')
register=set()
output = []
positions = []
for word in words:
if word not in register:
output.append(word)
register.add(word)
for word in words:
for index in range(len(output)):
if word == output[index]:
positions.append(index)
return output, positions
def write(path, output, positions):
with open(path, 'w') as f:
f.write(str(len(positions)) + '\n')
for index in positions:
f.write(str(index) + '\n')
f.write(str(len(output)) + '\n')
for word in output:
f.write(word + '\n')
def read(path):
words = []
positions = []
with open(path, 'r') as f:
poscount = int(f.readline().strip())
while poscount:
line = f.readline().strip()
pos = int(line)
positions.append(pos)
poscount -= 1
wordcount = int(f.readline().strip())
while wordcount:
line = f.readline()
word = line.strip()
words.append(word)
wordcount -= 1
output = []
for index in positions:
word = words[index]
output.append(word)
return output, positions
def main():
sentence = input('What is your Statement?:')
path = input('Name your file:')
if not path.endswith(".txt"):
path +=".txt"
source_out, source_positions = parse(sentence)
write(path, source_out, source_positions)
read_out, read_positions = read(path)
print("your file is: {}".format(read_out))
if __name__ == "__main__":
main()
此代码仍然过于复杂恕我直言,但至少它很可读,不使用任何全局,并且应该更容易测试。