wolframalpha api syntax error - python-2.7

i am working on 'wolframalpha' api and i am keep getting this error, i tried to search but not getting any working post on this error if you know please help me to fix this error
File "jal.py", line 9
app_id=’PR5756-H3EP749GGH'
^
SyntaxError: invalid syntax
please help; i have to show project tomorrow :(
my code is
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wolframalpha
import sys
app_id=’PR5756-H3EP749GGH'
client = wolframalpha.Client(app_id)
query = ‘ ‘.join(sys.argv[1:])
res = client.query(query)
if len(res.pods) > 0:
texts = “”
pod = res.pods[1]
if pod.text:
texts = pod.text
else:
texts = “I have no answer for that”
# to skip ascii character in case of error
texts = texts.encode(‘ascii’, ‘ignore’)
print texts
else:
print “Sorry, I am not sure.”

You used a backtick (´) instead of a single-quote (').
app_id='PR5756-H3EP749GGH'
Python directly shows you the error.
Also, use an editor with text highlighting.

Related

SyntaxError: invalid syntax using pipes.quote

Trying to create a shell script on a raspi3 in python to start a webcam. Getting a syntax error when trying to run the script.
Keep in mind I am new to Python but I have tried each individually to see what prints out, only getting this when I combine the script..
from gpiozero import Button
from pipes import quote
import time
import os
print("your script has started")
camOutput = 'output_http.so -w ./www'
camInput = 'input_raspicam.so -hf'
camStart = '/home/pi/projects/mjpg-streamer/mjpg_streamer -o'.format(quote(camOutput)).'-i'.format(quote(camInput))
print("your script is loaded")
stopButton = Button(26) #shutdown
camButton = Button(25) #web cam
ledButton = Button(24) #top led
while True:
if stopButton.is_pressed:
time.sleep(1)
if stopButton.is_pressed:
os.system("shutdown now -h")
time.sleep(1)
camStart = '/home/pi/projects/mjpg-streamer/mjpg_streamer -o'.format(quote(camOutput)).'-i'.format(quote(camInput))
^
SyntaxError: invalid syntax```
In Python, the dot operator is not used to concatenate strings, only to access properties and methods of an object. Thus, putting a string literal after a dot, such as .'-i', is a syntax error.
You probably want to do something like this, using the format method to replace the {} placeholders with the provided values:
camStart = '/..../mjpg_streamer -o {} -i {}'.format(quote(camOutput),quote(camInput))

Read & write txt file error - 'str' object has no attribute 'name', polish dialectical chars in path error

I use Python 2.7 on Win 7 Pro SP1.
I try code:
import os
path = "E:/data/keyword"
os.chdir(path)
files = os.listdir(path)
query = "{keyword} AND NOT("
result = open("query.txt", "w")
for file in files:
if file.endswith(".txt"):
file_path = file.name
dane = open(file_path, "r")
query.append(dane)
result.append(" OR ")
result.write(query)
result.write(")")
result.close()
I get error:
file_path = file.name AttributeError: 'str' object has no attribute
'name'
I can't figure why.
I have secon error when path is with polish dialectical chars like "ąęłńóżć". I get error for:
path = "E:/Bieżące projekty/keyword"
I try fix it to:
path =u"E:/Bieżące projekty/keyword"
but it not help. I'm starting with Python and I can't find out why this code is not working.
What i want
Find all text file in the directory.
Join all text file in one file text named "query.txt"
fx.
file 1
data1 data2
file 2
data 3 data 4
Output from "query.txt":
data1 data2 data 3 data 4
Above code working fine when path variable is without polish dialectical characters. When I change path I get error:
SyntaXError: Non-ASCII character '\xc5' in file query.py on line 9, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
On python doc PEP263 I find magic quote. Polish lang coding characters like "ąęłńóźżć" standard is ISO-8859-2. So i try add encoding to code. I try use UTF-8 too and I get the same error. My all code is (without 5 first lines with comment what code doing):
import os
#path = r"E:/data"
# -*- coding: iso-8859-2 -*-
path = r"E:/Bieżące przedsięwzięcia"
os.chdir(path)
files = os.listdir(path)
query = "{keyword} AND NOT("
for file in files:
if file.endswith(".txt"):
dane = open(file, "r")
text = dane.read()
query += text
print(query)
dane.close()
query.join(" OR ")
result = open("query.txt", "w")
result.write(query)
result.write(")")
result.close()
On Unicode/UTF-8 character here I found that polish char "ż" is coded in UTF-8 as "\xc5\xbc". Mark # to coding line with path with "ż" as comment make error too. When I remove line with this char code:
path = r"E:/Bieżące przedsięwzięcia"
working fine and I get result which I want.
For editing I use Notepad++ with default setings. I only set in python code tab replace by four space.
*
Second Question
I try find in Python doc in variable path what r does mean. I can't find it in Python 2.7 string documentation. Could someone tell my how this part of Python (like u, r before string value) is named fx.
path = u"somedata"
path = r"somedata"?
I would get doc to read about it.

Python script to convert adblock list in a forbidden file for Polipo proxy (regex)

On my system I currently running Polipo proxy, mainly for adblock purposes.
By a search on internet I've found many shell scripts to convert adblock plus lists in Polipo forbidden file format; most of these scripts rely on sed, ruby or python.
However none of them is able to generate a valid forbidden file: when I restart Polipo with the new generated forbidden file, in the Polipo's log file I see the message: "Couldn't compile regex: Unmatched ( or \("
The following python script which I attempt to use, is intended to convert an easylist file in a Polipo's forbidden file format:
#!/bin/python
# convert adblock ruleset into polipo-forbidden format
if __name__ == "__main__":
import os
import sys
import re
if len(sys.argv) == 1:
sys.exit("Usage: %s <adblockrules>" % os.path.basename(sys.argv[0]))
if not os.path.exists(sys.argv[1]):
sys.exit("The rules file (%s) doesn't exist" % sys.argv[1])
fhandle = file(sys.argv[1])
lines = fhandle.readlines()
fhandle.close()
dollar_re = re.compile("(.*?)\$.*")
for line in lines:
if line:
if (line[0] in ("[", "!", "~", "#", "#") or
line.startswith("/adverti") or
"##" in line):
continue
line = dollar_re.sub(r"\1", line)
# line = line.replace("|http://", "")
line = line.replace("|", "")
line = line.replace("||", "")
line = line.replace(".", r"\.")
line = line.replace("*", ".*")
line = line.replace("?", r"\?")
line = line.replace("^", r"[\/:\.=&\?\+\-\ ]+")
# line = line.replace("&", r"\&")
# line = line.replace("+", r"\+")
# line = line.replace("-", r"\-")
# line = line.replace(";", r"\;")
# line = line.replace("=", r"\=")
# line = line.replace("/", r"\/")
print(line.strip())
print("")
But as I've said, when I actualize this forbidden file, Polipo will claim "Couldn't compile regex: Unmatched ( or \("
This one is the forbidden file generated by the script
http://wikisend.com/download/494664/forbidden.conf
As I've said, online, there are many scripts like the one which I use, some of them also relies on sed, but no one seems able to generate a valid forbidden file (Polipo will always claims "Couldn't compile regex").
This is not a Polipo's fault, because if I made a clean forbidden file with some web url inside, Polipo will properly block these connections.
Can someone help me and explain how to modify/make a proper script to convert adblock lists in a valid regex forbidden file for Polipo?
Many thanks.
You can convert an Adblock rule to a Python regex using https://github.com/scrapinghub/adblockparser library:
>>> from adblockparser import AdblockRule
>>> rule = AdblockRule("/ad/loaders/*")
>>> print(rule.regex)
/ad/loaders/.*
I'm not sure Polipo suports the same regex format though; regexes can get pretty hairy:
>>> print(AdblockRule("||example.com$").regex)
^(?:[^:/?#]+:)?(?://(?:[^/?#]*\.)?)?example\.com
Also take care of rules with options; it may be better to remove them because semantics is different.
Hope this helps.

PyCharm issue on encoding

I am trying pycharm and facing an encoding issue. Can you please help resolve it.
code:
# -*- coding: utf-8 -*-
__author__ = 'me'
import os, sys
def main():
print repeat('mike',False)
print repeat('mok', True)
"""
comments here..
"""
def repeat(s,exclaim):
result = s*3
if exclaim:
result = result +'!!!'
return result
if __name__ == '__main__':
main()
error:
C:\Python27\python.exe C:\Python27\python.exe C:/Users/prakashs/PycharmProjects/GooglePython/WarmUp.py
File "C:\Python27\python.exe", line 1
SyntaxError: Non-ASCII character '\x90' in file C:\Python27\python.exe on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
Process finished with exit code 1
I have set the default encoding in pycharm to utf-8 as well. but i need to know where in pycharm we have to edit the settings.
Thank you.
Googling for Non-ASCII character '\x90' in file gives Using #-*- coding: utf-8 -*- does not remove "Non-ASCII character '\x90' in file hello.exe on line 1, but no encoding declared" error Stackoverflow question as the first hit. There you'll find answer to your question.
You have wrong command starting with C:\Python27\python.exe C:\Python27\python.exe... (python.exe is mentioned twice) which means you try to run executable (python.exe) instead of script file (WarmUp.py).

Selecting nodes with non-ASCII characters in Scrapy

I have the following simple web scraper written in Scrapy:
#!/usr/bin/env python
# -*- coding: latin-1 -*-
from scrapy.http import Request
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
class MySpiderTest(BaseSpider):
name = 'MySpiderTest'
allowed_domains = ["boliga.dk"]
start_urls = ["http://www.boliga.dk/bbrinfo/3B71489C-AEA0-44CA-A0B2-7BD909B35618",]
def parse(self, response):
hxs = HtmlXPathSelector(response)
item = bbrItem()
print hxs.select("id('unitControl')/div[2]/table/tbody/tr[td//text()[contains(.,'Antal Badeværelser')]]/td[2]/text()").extract()
but when I run the spider I get the following syntax error:
SyntaxError: Non-ASCII character '\xe6' in file... on line 32, but no encoding declared
because of the æ in the xpath. The xpath is working in Xpath Checker for Firefox. I tried URL-encoding the æ, but that didn't work. What am I missing?
thanks!
UPDATE: I have added the encoding declaration in the beginning of the code (Latin-1 should support Danish characters)
Use a unicode string for your XPath expression
hxs.select(u"id('unitControl')/div[2]/table/tbody/tr[td//text()[contains(.,'Antal Badeværelser')]]/td[2]/text()").extract()
or
hxs.select(u"id('unitControl')/div[2]/table/tbody/tr[td//text()[contains(.,'Antal Badev\u00e6relser')]]/td[2]/text()").extract()
See Unicode Literals in Python Source Code
SyntaxError: Non-ASCII character ‘\xe2′ in file … on line 40,
but no decoding declared …
This is caused by the replacing standard characters like apostrophe (‘) by non-standard characters like quotation mark (`) during copying.
Try to edit the text copied from pdf.
repsonse.xpath("//tr[contains(., '" + u'中文字符' + "')]").extract()