如何将长字符串中两词合并为一词并筛选含该词的句子?
Absolutely, this is totally achievable with basic text processing—let me break down how to do it clearly:
Step 1: Convert "split ratio" to "split-ratio"
First, we need to replace every occurrence of the two-word phrase with the hyphenated single term. Regular expressions work great here because they can target the exact phrase without accidentally matching similar words elsewhere.
Step 2: Keep only sentences containing "split-ratio"
Next, we split the text into individual sentences, then filter out any sentence that doesn’t include our hyphenated term. We’ll make sure to handle standard sentence-ending punctuation (like periods) when splitting.
Example Implementation (Python)
Here’s a hands-on code snippet that does both tasks:
import re original_text = """Given the large category of plants, the split ratio was determined to be 88.4. However, we're not sure if the split ratio was consistent across all subcategories or just a calculated average. If however, it deviated, it would be nonetheless, quite strange. The words - split ratio .""" # Replace "split ratio" with hyphenated version modified_text = re.sub(r'split ratio', 'split-ratio', original_text) # Split text into sentences (preserving punctuation) sentences = re.split(r'(?<=[.!?])\s+', modified_text) # Filter to keep only sentences with "split-ratio" filtered_sentences = [sentence for sentence in sentences if 'split-ratio' in sentence] # Combine back into a single string final_output = ' '.join(filtered_sentences) print(final_output)
Output
Given the large category of plants, the split-ratio was determined to be 88.4. However, we're not sure if the split-ratio was consistent across all subcategories or just a calculated average.
How It Works
- The regex
r'split ratio'finds the exact phrase to replace, ensuring we don’t alter other text. r'(?<=[.!?])\s+'splits the text after sentence-ending punctuation, so we don’t lose periods or other sentence markers.- The list comprehension filters out any sentence that lacks our hyphenated term, leaving only the two sentences you want.
内容的提问来源于stack exchange,提问作者Rahul Dev

