gpt4 book ai didi

python - 在 Python 中打印表格

转载 作者:太空宇宙 更新时间:2023-11-04 10:56:27 24 4
gpt4 key购买 nike

我正在尝试用 python 打印一个简单的表格,但之前的答案似乎都不是我要找的。我们将不胜感激任何帮助。

我有一个(文本)列表:

texts = [caesar,hamlet,macbeth,emma,persuasion,sense]

然后我运行一个名为“相似性”的函数,它比较 2 个文本。我想在表格中打印结果,但在打印语句遍历列表的一个循环后,我似乎无法换行。 [注意:我使用的是 Python 2.6.6,因为我使用的是 Natural Language Toolkit,一个用于语言学的 python 模块。]

这是我当前的打印语句,它不能正常工作:

for x in texts:
for y in texts:
print round(similarity(x,y),2),
if texts.index(x) == len(texts):
print '\n'

任何指向正确方向的指示都会很棒!

最佳答案

将列表中的每个项目与(另一个或相同的)列表中的每个项目进行比较的过程在数学上称为 Cartesian product . Python 有一个内置函数可以执行此操作:itertools.product这相当于嵌套的 for 循环:

假设 A 和 B 是列表:

for x in A:
for y in B:
print (x,y)

可以写成generator expression作为:

for pair in ((x,y) for x in A for y in B):
print pair

或者,更简洁:

from itertools import product
for pair in product(A, B):
print pair

在您的情况下,您将列表的所有项目与其自身进行比较,因此您可以编写 product(texts, texts),但 product 具有可选的关键字参数 repeat 对于这种情况:product(A, repeat=4)product(A, A, A, A) 相同。

您现在可以像这样重写您的代码:

from itertools import product

caesar = """BOOK I
I.--All Gaul is divided into three parts, one of which the Belgae
inhabit, the Aquitani another, those who in their own language are
called Celts, in ours Gauls, the third. All these differ from each other
in language, customs and laws."""

hamlet = """Who's there?"
"Nay, answer me. Stand and unfold yourself."
"Long live the King!"
"Barnardo!"
"He." (I.i.1-5)"""

macbeth = """ACT I SCENE I A desert place. Thunder and lightning.
[Thunder and lightning. Enter three Witches]
First Witch When shall we three meet again
In thunder, lightning, or in rain?
Second Witch When the hurlyburly's done,
When the battle's lost and won."""

texts = [caesar, hamlet, macbeth]

def similarity(x, y):
"""similarity based on length of the text,
substitute with similarity function from Natural Language Toolkit"""
return float(len(x))/len(y)


for pair in product(texts, repeat=2):
print "{}".format(similarity(*pair))

关于python - 在 Python 中打印表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9483498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com