इससे पहले कि मैं इस पर एक बड़ा पार्सर चलाऊं, मैं टेक्स्ट फ़ाइल से हैश # से शुरू होने वाली टिप्पणियों को फ़िल्टर करना चाहता हूं।
इसके लिए मैं यहां बताए अनुसार सप्रेस का उपयोग करता हूं।
PythonStyleComment काम नहीं करता है, क्योंकि यह उद्धरणों को अनदेखा करता है और इसके भीतर की सामग्री को हटा देता है। उद्धृत स्ट्रिंग में हैश कोई टिप्पणी नहीं है। यह स्ट्रिंग का हिस्सा है और इसलिए इसे संरक्षित किया जाना चाहिए।
यहाँ मेरा पाइस्टेस्ट है जिसे मैंने अपेक्षित व्यवहार का परीक्षण करने के लिए पहले ही लागू कर दिया है।
def test_filter_comment():
teststrings = [
'# this is comment', 'Option "sadsadlsad#this is not a comment"'
]
expected = ['', 'Option "sadsadlsad#this is not a comment"']
for i, teststring in enumerate(teststrings):
result = filter_comments.transformString(teststring)
assert result == expected[i]
मेरा वर्तमान कार्यान्वयन कहीं पाइपर्सिंग में टूट जाता है। मैं शायद कुछ ऐसा करता हूं जिसका इरादा नहीं था:
filter_comments = Regex(r"#.*")
filter_comments = filter_comments.suppress()
filter_comments = filter_comments.ignore(QuotedString)
के साथ विफल:
*****/lib/python3.7/site-packages/pyparsing.py:4480: in ignore
super(ParseElementEnhance, self).ignore(other)
*****/lib/python3.7/site-packages/pyparsing.py:2489: in ignore
self.ignoreExprs.append(Suppress(other.copy()))
E TypeError: copy() missing 1 required positional argument: 'self'
टिप्पणियों को सही तरीके से अनदेखा करने में कोई मदद मददगार होगी।
2 जवाब
आह मैं बहुत करीब था। मेरे पास निश्चित रूप से कोटेडस्ट्रिंग क्लास को तुरंत चालू करना है। निम्नलिखित अपेक्षित कार्य करता है:
filter_comments = Regex(r"#.*")
filter_comments = filter_comments.suppress()
qs = QuotedString('"') | QuotedString("'")
filter_comments = filter_comments.ignore(qs)
यहाँ कुछ और परीक्षण हैं।
def test_filter_comment():
teststrings = [
'# this is comment', 'Option "sadsadlsad#this is not a comment"',
"Option 'sadsadlsad#this is not a comment'",
"Option 'sadsadlsad'#this is a comment"
]
expected = [
'', 'Option "sadsadlsad#this is not a comment"',
"Option 'sadsadlsad#this is not a comment'",
"Option 'sadsadlsad'"
]
for i, teststring in enumerate(teststrings):
result = filter_comments.transformString(teststring)
assert result == expected[i]
आप जिस रेगेक्स का उपयोग कर रहे हैं वह सही नहीं है।
मुझे लगता है कि आपका मतलब था:
^\#.*
या
^(?:.*)\#.*
संबंधित सवाल
जुड़े हुए प्रश्न
नए सवाल
pyparsing
Pyparsing मॉड्यूल सरल व्याकरण बनाने और निष्पादित करने के लिए एक वैकल्पिक दृष्टिकोण है, बनाम पारंपरिक lex / yacc दृष्टिकोण, या नियमित अभिव्यक्ति का उपयोग। Pyparsing मॉड्यूल क्लायंट की एक लाइब्रेरी प्रदान करता है जिसे क्लाइंट कोड व्याकरण कोड में सीधे व्याकरण के निर्माण के लिए उपयोग करता है।