You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现CSV多字段条目全配对及指定格式文本生成

Solution to Generate All Breakfast-Person Pairs from CSV

Here's a straightforward Python script that reads your CSV file, creates every possible pairing between breakfast items and people, and outputs them exactly in the format you need:

import csv
from itertools import product

# Initialize lists to store our data
breakfast_items = []
people = []

# Read the input CSV file
with open('input.csv', 'r') as csv_file:
    # Use DictReader to access columns by their named headers
    reader = csv.DictReader(csv_file)
    for row in reader:
        # Clean up values and add to respective lists (skip empty entries)
        item = row['col1'].strip()
        if item:
            breakfast_items.append(item)
        person = row['col2'].strip()
        if person:
            people.append(person)

# Generate all pairs and write to the output text file
with open('output.txt', 'w') as output_file:
    # Use enumerate to get sequential numbering starting at 1
    for entry_num, (item, person) in enumerate(product(breakfast_items, people), start=1):
        # Format each line to match your requested structure
        output_line = f"breakfast_{entry_num} breakfast_item {item} person {person}"
        output_file.write(output_line + '\n')

How This Works:

  1. Reading the CSV: We use csv.DictReader to easily pull values from the col1 (breakfast items) and col2 (people) columns. We strip any extra whitespace from each entry and skip blanks to avoid invalid pairs.
  2. Creating All Pairs: The itertools.product function handles the Cartesian product of the two lists—this means every breakfast item gets paired with every person, no matter how many entries are in each column. Perfect for when your column lengths don't match!
  3. Writing Output: We loop through each pair with an incrementing number (starting at 1), format each line to your exact specification, and write it to a text file.

Quick Tips:

  • Swap 'input.csv' with the actual file path of your CSV.
  • Change 'output.txt' to your preferred output file name or path.
  • If one column is completely empty, the output file will be blank (since there are no valid pairs to generate).

内容的提问来源于stack exchange,提问作者thinguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:42:45