6

写入文本文件时,某些 file.write 实例后跟输出文件中的换行符,而其他实例则没有。我想要换行符,除非我告诉它们发生。代码:

    for doc,wc in wordcounts.items(): 
        out.write(doc)             #this works fine, no linebreak
        for word in wordlist: 
            if word in wc: out.write("\t%d" % wc[word]) #linebreaks appear
            else: out.write("\t0")                      #after each of these
        out.write("\n")        #this line had mixed spaces/tabs

我错过了什么?

更新

我应该从代码如何粘贴到 SO 中获得线索。出于某种原因,最后一行中混合了空格和制表符,因此在 TextMate 中,它在视觉上出现在“for word...”循环之外——但解释器将其视为该循环的一部分。将空格转换为制表符解决了这个问题。

感谢您的输入。

4

4 回答 4

13

file.write()如果您编写的字符串不包含任何\ns,则不会添加任何换行符。

但是您使用 强制为单词列表中的每个单词换行out.write("\n"),这是您想要的吗?

    for doc,wc in wordcounts.items(): 
        out.write(doc)             #this works fine, no linebreak
        for word in wordlist: 
            if word in wc: out.write("\t%d" % wc[word]) #linebreaks appear
            else: out.write("\t0")                      #after each of these
            out.write("\n") #<--- NEWLINE ON EACH ITERATION!

也许你缩进out.write("\n")太远了???

于 2009-12-01T14:14:24.473 回答
1

你在每个单词后写一个换行符:

for word in wordlist:
    ...
    out.write("\n")

这些是您看到的换行符,还是还有更多的换行符?

于 2009-12-01T14:13:10.450 回答
1

您可能需要strip()对每个wc[word]. 从 is 打印单个项目wc可能足以确定导致此行为的那些项目上是否已经存在换行符。

无论是那个还是你最终的缩进out.write("\n")都没有做你想要做的事情。

于 2009-12-01T14:19:45.710 回答
0

我认为你的缩进是错误的。

(我也冒昧地使您的 if 子句变得多余并且代码更具可读性:)

for doc,wc in wordcounts.items()
   out.write(doc)
   for word in wordlist:
     out.write("\t%d" % wc.get(word,0))
   out.write("\n")
于 2009-12-01T14:21:19.420 回答