发布网友 发布时间:2022-04-06 14:19
共1个回答
热心网友 时间:2022-04-06 15:49
#! /usr/bin/python
# -*- coding: gb2312 -*-
import sys
import nltk
from nltk.corpus import brown
class stdoutToStr:
def __init__(self):
self.s = ''
def write(self, buf):
self.s += buf
_out = sys.stdout
out = stdoutToStr()
sys.stdout = out
days = ['Monday','Tuesday','Wednesday','Yhursday','Friday','Saturday','Sunday']
cfd =nltk.ConditionalFreqDist(
(genre,word)
for genre in ['news','romance']
for word in brown.words(categories=genre)
)
stdout=cfd.tabulate(samples=days)
sys.stdout = _out
a= out.s
for i in a.split('\n'):
b= i.split(' ')
while '' in b:
b.remove('')
if a.index(i)==0:
b.insert(0,' ')
for j in b:
print j.center(10," "),
print '\n'
此问题 1.要输出重定向 到cfd.tabulate(samples=days) 这个输出到变量
使变量a得到
''' Monday Tuesday Wednesday Yhursday Friday Saturday Sunday
news 54 43 22 0 41 33 51
romance 2 3 3 0 3 4 5 '''
2. 输出对齐 print j.center(10," "),
格式不满意 可以用以下参考做调整
word="version3.0"
print word.center(20) #居中输出,总共20个字符,word左右两侧各输出5个空格
print word.center(20,"*") #居中输出,总共20个字符,word左右两侧各输出5个"*"号
print word.ljust(0) #左对齐输出
print word.rjust(20) #右对齐输出,总共20个字符,word占10个字符,因此左侧填充一个空格再输出word
print "0s"%word #类似于word.rjust(30
3.附上程序截图