Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将NLTK表格结果输出到CSV?_Python_Nltk - Fatal编程技术网

Python 如何将NLTK表格结果输出到CSV?

Python 如何将NLTK表格结果输出到CSV?,python,nltk,Python,Nltk,我有以下资料: fdist = FreqDist(text) 我想将以下制表结果输出到CSV中(与python控制台相反) 如何执行此操作?您可以查看(复制)并根据需要更改打印语句,以编写CSV文件。源代码复制如下: def tabulate(self, *args, **kwargs): """ Tabulate the given samples from the frequency distribution (cumulative), displaying

我有以下资料:

fdist = FreqDist(text)
我想将以下制表结果输出到CSV中(与python控制台相反)

如何执行此操作?

您可以查看(复制)并根据需要更改打印语句,以编写CSV文件。源代码复制如下:

def tabulate(self, *args, **kwargs): 
    """ 
    Tabulate the given samples from the frequency distribution (cumulative), 
    displaying the most frequent sample first.  If an integer 
    parameter is supplied, stop after this many samples have been 
    plotted.  If two integer parameters m, n are supplied, plot a 
    subset of the samples, beginning with m and stopping at n-1. 
    (Requires Matplotlib to be installed.) 

    @param samples: The samples to plot (default is all samples) 
    @type samples: C{list} 
    """ 
    if len(args) == 0: 
       args = [len(self)] 
    samples = list(islice(self, *args)) 

    cumulative = _get_kwarg(kwargs, 'cumulative', False) 
    if cumulative: 
       freqs = list(self._cumulative_frequencies(samples)) 
    else: 
       freqs = [self[sample] for sample in samples] 
    # percents = [f * 100 for f in freqs]  only in ProbDist? 

    for i in range(len(samples)): 
       print "%4s" % str(samples[i]), 
    print 
    for i in range(len(samples)): 
       print "%4d" % freqs[i], 
    print 

您可以将
FreqDist
视为
dict
,并使用
csv
模块。例如:

from nltk import FreqDist
import csv

fdist = FreqDist("aaa b cccc dd e")

with open("fdist.csv", "wb") as fp:
    writer = csv.writer(fp, quoting=csv.QUOTE_ALL)
    writer.writerows(fdist.items())
产生

>>> !cat fdist.csv
" ","4"
"c","4"
"a","3"
"d","2"
"b","1"
"e","1"
>>> !cat fdist.csv
" ","4"
"c","4"
"a","3"
"d","2"
"b","1"
"e","1"