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

如何提取字母Y之后的字符串并写入CSV文件?

提取每行Y之后内容的CSV转换代码

Hey there, I see you need to tweak your existing text-to-CSV script to only grab the parts of each line that come after the letter "Y". Let's adjust that code to do exactly what you need:

import csv

txt_file = r"input.txt"
csv_file = r"Good_data.csv"

# Use context managers to handle files safely (no need to manually close them)
with open(txt_file, "r") as infile, open(csv_file, 'w', newline='') as outfile:
    reader = csv.reader(infile, delimiter=',')
    writer = csv.writer(outfile)
    
    for row in reader:
        processed_cells = []
        for cell in row:
            # Find the first position of "Y" in the cell
            y_pos = cell.find('Y')
            if y_pos != -1:
                # Extract everything after Y, and trim extra whitespace
                extracted = cell[y_pos + 1:].strip()
                processed_cells.append(extracted)
            else:
                # If there's no Y in the cell, keep the original content (trimmed)
                processed_cells.append(cell.strip())
        # Write the processed row to CSV
        writer.writerow(processed_cells)

Key changes and explanations:

  • Safe file handling: Used with statements to open files—this ensures files are automatically closed when we're done, avoiding resource leaks.
  • Per-cell processing: Instead of writing rows directly, we loop through each cell in the row to find and extract content after the first "Y".
  • Whitespace cleanup: Added .strip() to remove any leading/trailing spaces from the extracted content (like the space before Y'ay' TQ in your example, which becomes 'ay' TQ after processing).
  • Fallback for no Y: If a cell doesn't contain "Y", it just keeps the original trimmed content (you can change this to skip the cell entirely by replacing processed_cells.append(cell.strip()) with pass if that's what you need).

For your example input line:

u'gY': -0.009,Y'gm': 0.0011, Y'ay' TQ

The processed CSV row will be:
: -0.009, 'gm': 0.0011, 'ay' TQ

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:37:53