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

Python读取文本文件生成含固定键的字典实现方案

Solution to Parse Text Line into Target Dictionary

Here's a straightforward way to parse your specific text line into the desired dictionary in Python:

Since your input has a consistent structure (two-word title, single-word name, single-word date, then the full feedback text), we can use a targeted split to extract each component cleanly without breaking the feedback content.

Code Implementation

# Read the single line from your text file
with open('your_file.txt', 'r') as file:
    input_line = file.read().strip()  # Remove any accidental leading/trailing whitespace

# Split the line into 5 distinct parts (stopping after 4 splits to preserve feedback)
split_parts = input_line.split(maxsplit=4)

# Build the dictionary with the required keys
result_dict = {
    'title': ' '.join(split_parts[:2]),
    'name': split_parts[2],
    'date': split_parts[3] + ' ',  # Adding trailing space to match your expected output
    'feedback': split_parts[4]
}

# Verify the result
print(result_dict)

Expected Output

Running this code will generate exactly the dictionary you specified:

{'title': 'Thank you', 'name': 'binhnguyen', 'date': '2010-09-12 ', 'feedback': 'I want to say thank you to all of you.'}

Quick Note on the Date Field

If the trailing space in the date value was a typo, you can simply remove the + ' ' portion from the dictionary entry to get '2010-09-12' instead.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 06:34:08