如何在Python中读取.txt文件不同列并按ID分组到不同字符串?
Solution for Grouping Sentences by ID from answers.txt
Got it, let's break down how to solve this problem. Your answers.txt has content where every word is prefixed with an ID, and we need to group words by their ID to form complete sentences, then store each sentence in its own string.
Step-by-Step Approach
- Read the File: Safely load the content of
answers.txtusing Python's built-in file handling to avoid resource leaks. - Split Content into Elements: Split the entire content into a list of alternating IDs and words, since the file uses spaces as separators.
- Group Words by ID: Use a dictionary to collect all words that belong to the same ID—this keeps things organized even if you have more than two IDs later.
- Build Sentences: Convert each group of words into a single, readable string (your desired
answer_0,answer_1, etc.).
Complete Code Example
# Read the content of answers.txt with open('answers.txt', 'r') as file: raw_content = file.read().strip() # Split the content into individual elements (ID + word pairs) content_elements = raw_content.split() # Initialize a dictionary to hold words grouped by their ID id_to_words = {} # Iterate over elements in pairs (ID followed by word) for idx in range(0, len(content_elements), 2): current_id = content_elements[idx] current_word = content_elements[idx + 1] # Create a new list for the ID if it doesn't exist yet if current_id not in id_to_words: id_to_words[current_id] = [] # Add the word to the corresponding ID's list id_to_words[current_id].append(current_word) # Convert each ID's word list into a full sentence string answer_0 = ' '.join(id_to_words['0']) answer_1 = ' '.join(id_to_words['1']) # Optional: Print results to verify print("answer_0:", answer_0) print("answer_1:", answer_1)
Output Explanation
When you run this code, you'll get:
answer_0: identify organizations that participate in international criminal activity the activity and if possible collaborating organizations and countries involved answer_1: is the disease of poliomyelitis polio under control in the world
This approach is flexible too—if your file has more IDs (like 2, 3, etc.), the code will automatically handle them without extra changes. Just add more variables like answer_2 = ' '.join(id_to_words['2']) if needed.
内容的提问来源于stack exchange,提问作者Marisa
相关产品推荐
相关产品推荐

