简体   繁体   English

将for循环output保存到txt

[英]Saving for loop output into txt

Im stuck in saving this for loop results, I've searched in stack all kind to save output of the for loop but I did come a the right solution.我坚持保存这个for循环结果,我已经在堆栈中搜索了所有类型以保存for循环的output,但我确实找到了正确的解决方案。 My code is:我的代码是:

doc = sys.argv[1]
target = sys.argv[2]
fene = int(sys.argv[3])

a = open(file)
text = a.read() 
a.close()

tokens = text.split()
keyword = re.compile(target, re.IGNORECASE)

for index in range( len(tokens) ):
    if keyword.match( tokens[index] ):
        start = max(0, index-window)
        finish = min(len(tokens), index+window+1)
        lhs = " ".join( tokens[start:index] )
        rhs = " ".join( tokens[index+1:finish] )
        print("%s \t \t %s \t \t %s" % (lhs, tokens[index], rhs)) 

I tried f = open("output.txt", w) then at the end(line print) i've added f.write(lsm, tokens[index], rhs) this did not work.我尝试了f = open("output.txt", w)然后在最后(行打印)我添加了f.write(lsm, tokens[index], rhs)这不起作用。 Even bringing open() into for loop.甚至将 open() 带入 for 循环。 How too handle it?又该如何处理? UPDATE: output of for loop that I want in txt.更新:我想要在 txt 中的 for 循环的 output。 图片

@Michael answer explanation in comment. @Michael 在评论中回答解释。 Thanks谢谢

saveme = open('output.txt', 'w') 
for index in range( len(tokens) ):
    if keyword.match( tokens[index] ):
        start = max(0, index-window)
        finish = min(len(tokens), index+window+1)
        lhs = " ".join( tokens[start:index] )
        rhs = " ".join( tokens[index+1:finish] )
        print("%s \t \t %s \t \t %s" % (lhs, tokens[index], rhs), file=saveme)
saveme.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM