मेरे पास शब्दों की एक सूची है (find_list) जिसे मैं एक पाठ में खोजना चाहता हूं और उन शब्दों वाले भावों की एक सूची है जिन्हें मैं पाठ में होने पर (scape_list) बायपास करना चाहता हूं।
मैं इस कोड का उपयोग करके टेक्स्ट में सभी शब्द ढूंढ सकता हूं:
find_list = ['name', 'small']
scape_list = ['small software', 'company name']
text = "My name is Klaus and my middle name is Smith. I work for a small company. The company name is Small Software. Small Software sells Software Name."
final_list = []
for word in find_list:
s = r'\W{}\W'.format(word)
matches = re.finditer(s, text, (re.MULTILINE | re.IGNORECASE))
for word_ in matches:
final_list.append(word_.group(0))
अंतिम_सूची है:
[' name ', ' name ', ' name ', ' Name.', ' small ', ' Small ', ' Small ']
क्या scape_list में सूचीबद्ध अभिव्यक्तियों को बायपास करने और इस तरह एक final_list प्राप्त करने का कोई तरीका है:
[' name ', ' name ', ' Name.', ' small ']
Final_list और scape_list को हमेशा अपडेट किया जा रहा है। तो मुझे लगता है कि रेगेक्स एक अच्छा तरीका है।
1 उत्तर
आप रेगेक्स का उपयोग करके find_list
शब्द के पहले और बाद में शब्द को कैप्चर कर सकते हैं और जांच सकते हैं कि क्या दोनों संयोजन scape_list
में मौजूद नहीं हैं। मैंने टिप्पणियां जोड़ दी हैं जहां मैंने कोड बदल दिया है। (और बेहतर होगा कि scape_list को set
में बदल दें, अगर यह भविष्य में बड़ी हो सकती है)
find_list = ['name', 'small']
scape_list = ['small software', 'company name']
text = "My name is Klaus and my middle name is Smith. I work for a small company. The company name is Small Software. Small Software sells Software Name."
final_list = []
for word in find_list:
s = r'(\w*\W)({})(\W\w*)'.format(word) # change the regex to capture adjacent words
matches = re.finditer(s, text, (re.MULTILINE | re.IGNORECASE))
for word_ in matches:
if ((word_.group(1) + word_.group(2)).strip().lower() not in scape_list
and (word_.group(2) + word_.group(3)).strip().lower() not in scape_list): # added this condition
final_list.append(word_.group(2)) # changed here
final_list
['name', 'name', 'Name', 'small']
संबंधित सवाल
नए सवाल
python
पायथन एक बहु-प्रतिमान है, गतिशील रूप से टाइप किया हुआ, बहुउद्देशीय प्रोग्रामिंग भाषा है। यह एक साफ और एक समान वाक्यविन्यास सीखने, समझने और उपयोग करने के लिए त्वरित होने के लिए डिज़ाइन किया गया है। कृपया ध्यान दें कि अजगर 2 आधिकारिक तौर पर 01-01-2020 के समर्थन से बाहर है। फिर भी, संस्करण-विशिष्ट पायथन सवालों के लिए, [अजगर -२.०] या [अजगर -३.x] टैग जोड़ें। पायथन वेरिएंट (जैसे, ज्योथन, PyPy) या लाइब्रेरी (उदा।, पांडस और न्यूमपी) का उपयोग करते समय, कृपया इसे टैग में शामिल करें।