簡體   English   中英

如何在 CSV 文件的列之間生成所有可能的單詞組合?

[英]How to generate all possible word combinations between columns of a CSV file?

我想獲取一個 CSV 文件,其中每一列都是一個單詞類別,並在它們之間生成所有可能的組合 這是我用來測試腳本的簡化 CSV 文件(但將使用的 CSV 會更大,有十幾列或更多列):

$ cat file.csv 
Color,Pet,Action
black,dog,barks
brown,cat,runs
white,bird,flies
,hamster,
red,,swims

如您所見,某些列的單詞更多(例如,“colors”可能比“pets”多,或者“pets”比“actions”多)。

這是我到目前為止所擁有的:

import csv
import itertools

with open('file.csv', newline='') as csvfile:
    next(csvfile, None) #skip header row
    data = list(csv.reader(csvfile))

for combination in itertools.product(*data):
    print(combination)

這是我得到的 output 的摘錄:

$ python3 combiner.py 
('black', 'brown', 'white', '', 'red')
('black', 'brown', 'white', '', '')
('black', 'brown', 'white', '', 'swims')
('black', 'brown', 'white', 'hamster', 'red')
('black', 'brown', 'white', 'hamster', '')
('black', 'brown', 'white', 'hamster', 'swims')
('black', 'brown', 'white', '', 'red')
('black', 'brown', 'white', '', '')
('black', 'brown', 'white', '', 'swims')
('black', 'brown', 'bird', '', 'red')
('black', 'brown', 'bird', '', '')
[...]

我想完成的事情:

  • 同一 output 行中沒有來自同一類別(列)的多個項目
  • 刪除括號、引號和逗號(我相信我可以通過在打印之前將數組轉換為字符串來實現)

所以,舉一個 output 的例子,我想得到:

black
black dog
black dog barks
black dog runs
black dog flies
black dog swims
black cat
black cat barks
black cat runs
black cat flies
black cat swims
brown
brown dog
brown dog barks
[...]
black hamster
black hamster flies
[...]
red fish runs
[...]

如果有人對完成此任務的最有效方法(或特定庫或采取的方法)提出建議,我將不勝感激。

訣竅是在將列傳遞給 itertools.product 之前將它們組合在一起。

要打印不包含任何給定迭代的所有值的“black”和“black dog”之類的行,您可以將第一次迭代存儲為列表,然后在后續迭代中比較值,更新列表並打印值隨着值的變化而變化。

下面的解決方案可以推廣到任意數量的列。

import csv
import itertools

with open("file.csv", "r", newline="", encoding="utf-8") as csvfile:
    reader = csv.reader(csvfile)
    header_row = next(reader)
    columns = [[] for _ in header_row]
    for row in reader:
        for i, value in enumerate(row):
            if value:
                columns[i].append(value)

product_iter = itertools.product(*columns)
current_combination = list(next(product_iter))
for i in range(len(current_combination)):
    print(" ".join(current_combination[:i + 1]))

for combination in product_iter:
    for i in range(len(combination)):
        if combination[i] != current_combination[i]:
            current_combination[i] = combination[i]
            print(" ".join(current_combination[:i + 1]))

Output:

black
black dog
black dog barks
black dog runs
black dog flies
black dog swims
black cat
black cat barks
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM