I have used the following link for JavaScript grammar .
https://github.com/antlr/grammars-v4/tree/master/javascript/javascript/Python
i have used antlr4.8 and ntlr4-python3-runtime==4.8. when i use the following code it gives following error .
error:
PS N:\antlr4\sample\py4.8> python main.py test.js
Running
Test started for: test.js
Created parsers
Traceback (most recent call last):
File "main.py", line 25, in <module>
main(sys.argv)
File "main.py", line 20, in main
tree = parser.program()
File "N:\antlr4\sample\py4.8\JavaScriptParser.py", line 880, in program
self.enterRule(localctx, 0, self.RULE_program)
File "C:\Users\root\AppData\Local\Programs\Python\Python38\lib\site-packages\antlr4\Parser.py", line 366, in enterRule
self._ctx.start = self._input.LT(1)
.
.
.
File "N:\antlr4\sample\py4.8\JavaScriptLexer.py", line 919, in sempred
return pred(localctx, predIndex)
File "N:\antlr4\sample\py4.8\JavaScriptLexer.py", line 925, in HashBangLine_sempred
return this.IsStartOfFile()
NameError: name 'this' is not defined
code:
import sys
from antlr4 import *
import JavaScriptLexer
import JavaScriptParser
JSL = JavaScriptLexer.JavaScriptLexer
JSP = JavaScriptParser.JavaScriptParser
class WriteTreeListener(ParseTreeListener):
def visitTerminal(self, node:TerminalNode):
print ("Visit Terminal: " + str(node) + " - " + repr(node))
def main(argv):
input_stream = FileStream(argv[1])
print("Test started for: " + argv[1])
lexer = JSL(input_stream)
stream = CommonTokenStream(lexer)
parser = JSP(stream)
print("Created parsers")
tree = parser.program()
ParseTreeWalker.DEFAULT.walk(WriteTreeListener(), tree)
if __name__ == '__main__':
print("Running")
main(sys.argv)
print("Hello")
What have I done wrong ?
Replace this with self
(ref here). Example:
Change
return this.IsStartOfFile()
to
return self.IsStartOfFile().
Run the script transformGrammar.py, as indicated in documentation.
Related
I am making a coding language with Python. I am working on a module system for custom made modules.
The full code is at https://repl.it/#UCYT5040/koolCode and interp.py but the issue I am having is with this code:
for i in keywords:
keyword = i.lower()
if keyword == "print":
for i1 in quotes:
print(i1)
elif keyword == "add":
for i1 in quotes:
quote = i1.lower()
if quote == "python":
modulesInfo["python"] = {"runLang":"python","runpy":"{quote}"}
modules.append("python")
else:
print("koolCode WARN: custom modules not supported/module not found.")
else:
for i1 in modules:
if modulesInfo[i1]["runLang"] == "python":
try:
eval("f\"" + modulesInfo[i1][keyword] + "\"")
except KeyError:
print(f"koolCode ERROR: Module")
I get this error:
Welcome to koolCode console.
Would you like to open a file? y/n
n
A file will not be opened. Type any commands below.
koolCode>add "python"
['add'] ['python']
koolCode>runpy "help()"
Traceback (most recent call last):
File "main.py", line 8, in <module>
noFile()
File "main.py", line 3, in noFile
runString(input("koolCode>"))
File "/home/runner/koolCode/interp.py", line 46, in runString
eval("f\"" + modulesInfo[i1][keyword] + "\"")
File "<string>", line 1, in <module>
NameError: name 'quote' is not defined
How can I do this?
I installed corpcrawl but when I try to run this code from its documentation page:
from corpcrawl.crawler import CorpCrawl
from corpcrawl.backend import Backend
def main()
I get the following error
from corpcrawl.crawler import CorpCrawl
Traceback (most recent call last):
File "<ipython-input-40-a34fa6bf09cd>", line 1, in <module>
from corpcrawl.crawler import CorpCrawl
File "C:\ProgramData\Anaconda3\lib\site-packages\corpcrawl\crawler.py", line 1, in <module>
from parser import Parser
ImportError: cannot import name 'Parser'
def main()
File "<ipython-input-44-eaaf015e0d6b>", line 1
def main()
^
SyntaxError: invalid syntax
Why am I getting this error?
The code from corpcrawl's documentation page is broken:
Missing :
Wrong indentation
Illegal characters (such as “ instead of ")
Here is what it should look like (Python 2):
from corpcrawl.crawler import CorpCrawl
from corpcrawl.backend import Backend
class MyBackend(Backend):
def get_company(self, name):
pass
def add_company(self, comp):
print "Adding %s" % str(comp)
def main():
my_backend = MyBackend()
crawler = CorpCrawl(cache_path = '/an/absolute/path/to/some/dir', backend = my_backend)
c.crawl(years = [2011, 2012], quarters = [1, 2, 3, 4])
This is to test the class; however, I am getting an error and I do not know how to fix it.
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'"""
def test_first_last_name(self):
"""Do names like 'Mark James' work?"""
formatted_name = get_formatted_name('mark','James')
self.assertEqual(formatted_name,'Mark James')
unittest.main()
Here's the class that is being tested.
def get_formatted_name(first, last):
"""This is where the name is formatted correctly"""
full_name = first + " " + last
return full_name.title()
The error I am getting is this:
/Desktop/python_work/test_name_function.py", line 1, in <module>
import unittest
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/__init__.py", line 58, in <module>
from .result import TestResult
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/result.py", line 5, in <module>
import traceback
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/traceback.py", line 3, in <module>
import linecache
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/linecache.py", line 10, in <module>
import tokenize
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tokenize.py", line 96, in <module>
class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
AttributeError: 'module' object has no attribute 'namedtuple'
Anyone have a clue?
I believe you need to add if 'name' == 'main':
unittest.main() to your code.
The below code should fix the error -
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'"""
def test_first_last_name(self):
"""Do names like 'Mark James' work?"""
formatted_name = get_formatted_name('mark','James')
self.assertEqual(formatted_name,'Mark James')
if '__name__' == '__main__':
unittest.main()
I am using the Python pocket sphinx tutorial, according to
https://metakermit.com/2011/python-speech-recognition-helloworld/
(complete code here):
import sys,os
def decodeSpeech(hmmd,lmdir,dictp,wavfile):
"""
Decodes a speech file
"""
try:
import pocketsphinx as ps
import sphinxbase
except:
print """Pocket sphinx and sphixbase is not installed
in your system. Please install it with package manager.
"""
speechRec = ps.Decoder(hmm = hmmd, lm = lmdir, dict = dictp)
wavFile = file(wavfile,'rb')
wavFile.seek(44)
speechRec.decode_raw(wavFile)
result = speechRec.get_hyp()
return result[0]
if __name__ == "__main__":
hmdir = "/usr/share/pocketsphinx/model/hmm/en_US/"
lmd = "/usr/share/pocketsphinx/model/lm/en_US/hub4.5000.DMP"
dictd = "/usr/share/pocketsphinx/model/lm/en_US/cmu07a.dic"
wavfile = sys.argv[1]
recognised = decodeSpeech(hmdir,lmd,dictd,wavfile)
print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
print recognised
print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
and when I run it I get the following error message:
Traceback (most recent call last):
File "hello.py", line 30, in <module>
recognised = decodeSpeech(hmdir,lmd,dictd,wavfile)
File "hello.py", line 17, in decodeSpeech
speechRec = ps.Decoder(hmm = hmmd, lm = lmdir, dict = dictp)
TypeError: __init__() got an unexpected keyword argument 'hmm'
Could you help me?
Looking at the pocketsphinx code on GitHub, in decoder_test.py we have an example of how to pass options to Decoder.
So it looks like your tutorial is for an old version and you actually want:
config = ps.Decoder.default_config()
config.set_string('-hmm', hmmd)
config.set_string('-lm', lmdir)
config.set_string('-dict', dictp)
speechRec = ps.Decoder(config)
Python open function does not return file descriptor. Why could this be? I am using python 3.3.
test_file_open.py
#!/usr/bin/env python
import sys
if __name__ == '__main__':
html = ""
hmtl_fd = open("ns_temp.html",'r')
for line in html_fd:
html += line
Output:
Traceback (most recent call last):
File "./test_file_open.py", line 7, in <module>
for line in html_fd:
NameError: name 'html_fd' is not defined
Permissions:
-rwxr-xr-x 1 michael michael 160 Mar 16 23:03 test_file_open.py
There is a typo in a variable name, see hmtl_fd and html_fd.
Replace:
hmtl_fd = open("ns_temp.html",'r')
with:
html_fd = open("ns_temp.html",'r')
Typo: hmtl_fd in place of html_fd