Python:如何将输出捕获到文本文件? (现在仅捕获了530行中的25行) [英] Python: how to capture output to a text file? (only 25 of 530 lines captured now)
问题描述
我在SO上做了很多潜伏,在搜索和阅读上也做了很多,但我也必须承认,一般来说,在编程方面我是个相对的菜鸟.我正在尝试学习,所以我一直在使用Python的NLTK.在下面的脚本中,我可以使用所有内容,除了它只写多屏幕输出的第一个屏幕,至少这就是我的想法.
I've done a fair amount of lurking on SO and a fair amount of searching and reading, but I must also confess to being a relative noob at programming in general. I am trying to learn as I go, and so I have been playing with Python's NLTK. In the script below, I can get everything to work, except it only writes what would be the first screen of a multi-screen output, at least that's how I am thinking about it.
这是脚本:
#! /usr/bin/env python
import nltk
# First we have to open and read the file:
thefile = open('all_no_id.txt')
raw = thefile.read()
# Second we have to process it with nltk functions to do what we want
tokens = nltk.wordpunct_tokenize(raw)
text = nltk.Text(tokens)
# Now we can actually do stuff with it:
concord = text.concordance("cultural")
# Now to save this to a file
fileconcord = open('ccord-cultural.txt', 'w')
fileconcord.writelines(concord)
fileconcord.close()
这是输出文件的开头:
Building index...
Displaying 25 of 530 matches:
y . The Baobab Tree : Stories of Cultural Continuity The continuity evident
regardless of ethnicity , and the cultural legacy of Africa as well . This Af
我在这里缺少什么来将整个530个匹配项写入文件?
What am I missing here to get the entire 530 matches written to the file?
推荐答案
text.concordance(self, word, width=79, lines=25)
似乎具有与我看不到提取一致性索引大小的方法,但是,
I see no way to extract the size of concordance index, however, the concordance printing code seem to have this part: lines = min(lines, len(offsets))
, therefore you can simply pass sys.maxint
as a last argument:
concord = text.concordance("cultural", 75, sys.maxint)
已添加:
现在看您的原始代码,我看不到以前的工作方式. text.concordance
不返回任何内容,而是使用print
将所有内容输出到stdout
.因此,简单的选择是将stdout重定向到您的文件,如下所示:
Looking at you original code now, I can't see a way it could work before. text.concordance
does not return anything, but outputs everything to stdout
using print
. Therefore, the easy option would be redirection stdout to you file, like this:
import sys
....
# Open the file
fileconcord = open('ccord-cultural.txt', 'w')
# Save old stdout stream
tmpout = sys.stdout
# Redirect all "print" calls to that file
sys.stdout = fileconcord
# Init the method
text.concordance("cultural", 200, sys.maxint)
# Close file
fileconcord.close()
# Reset stdout in case you need something else to print
sys.stdout = tmpout
另一种选择是直接使用相应的类并省略Text包装器.只需从此处复制位,然后将它们与位合并从此处开始.
Another option would be to use the respective classes directly and omit the Text wrapper. Just copy bits from here and combine them with bits from here and you are done.
这篇关于Python:如何将输出捕获到文本文件? (现在仅捕获了530行中的25行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!