【问题标题】:display two pairs of words with a loop [duplicate]用循环显示两对单词[重复]
【发布时间】:2020-06-20 21:04:49
【问题描述】:

我有一个第一个 .txt 文件,每行包含 5 个单词,另一个包含 100 个关键字(每行也包含 100 个关键字)。我想为每个单词打印整个术语列表。这就是我所做的:

words = open("./sample_5.txt","r", encoding='utf8')
termes = open("./100_keywords.txt", "r", encoding='utf8')
for w in words:
    for t in termes:
        print (w,t)

问题是,这不会在 w 上迭代,这意味着它会返回给我第一个带有 100 关键字的单词,仅此而已。我应该有一个 (5,100) 的矩阵,我得到 (1,100)。有什么帮助吗?

【问题讨论】:

  • 我很难理解这个问题。你能给出某些输入的实际和预期输出的样本吗?也许在较小的文件上,比如第一个文件有 2 个单词,第二个文件有 3 个。

标签: python


【解决方案1】:

我认为这会有所帮助。

这里我们读取指定为行数组的文件(我们使用.readlines(),因为每个项目都在单独的行上)。 然后在这些行之间做一个cartesian product(相当于编写嵌套循环)。然后打印出来。

说明:

当我们处理文件(使用open)时,python 在内部创建一个流(TextIOBase),每次我们尝试从缓冲区读取时,下一次调用都会从上次中断的地方返回。因此,除非您在第二个循环中关闭/打开文件,或者从头开始读取,否则您将无法取回已经读取的字符串。在我给出的解决方案中,我们只读取了开头的文件一次。

from itertools import product

words = open("./a.txt","r", encoding='utf8').readlines()
termes = open("./b.txt", "r", encoding='utf8').readlines()

for word, term in product(words, termes):
    print(word.strip(), term.strip())

【讨论】:

  • 你能解释一下这个答案是如何工作的,而 OP 采取的方法却没有吗?
  • @quamrana 我试图提供一些解释,感谢您的建议
【解决方案2】:

已编辑 @Brian McCutchon 的评论

由于您想多次遍历第二个文件,
您想使用像列表这样的静态容器,
否则,您只能迭代一次:

words = open("./sample_5.txt","r", encoding='utf8')
termes = open("./100_keywords.txt", "r", encoding='utf8').read().splitlines()
for w in words:
    for t in termes:
        print (w,t)

【讨论】:

  • @BrianMcCutchon 在嵌套 for 循环中:对于 words 中的每个 w,OP 都在迭代 terms。所以 OP 正在尝试迭代第二个文件对象 terms 5 次。
  • 你说得对,我编辑了答案。
【解决方案3】:

你可以这样做:

with open("./sample_5.txt","r", encoding='utf8') as words, open("./100_keywords.txt", "r", encoding='utf8') as termes:
        a = termes.readlines()
        for w in words:
            for t in a:
                print (w,t.replace('\n',''))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多