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
相关产品推荐
相关产品推荐

