Python using grep to count word occurrences in directory [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
I'm trying to run
word = "where's"
os.popen(f"grep -ow '{word.replace("'", """'"'"'""")}' /texts/*.txt | wc -l").read()
I get:
File "<stdin>", line 1
os.popen(f"grep -ow '{word.replace("'", """'"'"'""")}' /texts/*.txt | wc -l").read()
^
SyntaxError: invalid syntax
Why would this be happening and how can I fix it?
If I escape the asterisk \* I get "Unexpected error after line continuation character" with the arrow pointing at the end of the line (after read())

You're trying to do too much complicated quoting all at once.
Instead, do it in two steps so the quoting doesn't conflict.
word = "where's"
word = word.replace("'", """'"'"'""")
os.popen(f"grep -ow '{word}' /texts/*.txt | wc -l").read()
To explain your error, it's because pairs of quotes do not nest in Python strings.
For example, you can't do this:
s = "alpha 'beta "gamma" delta' omega"
The double quote preceding alpha does not match up with the one following omega. It matches up with the very next double quote it sees, the one preceding gamma. The single quotes do not "protect" the double quotes.

Related

F strings giving syntax error in python 3.7.6 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
This code:
a = 10
b = 20
print(f "The variable a is {a} and the variable b is {b}.")
returns this error:
File "main.py", line 3
print (f "The variable a is {a} and the variable b is {b}")
^
SyntaxError: invalid syntax
The version I'm using is after 3.6, so it should work. I'm using Anaconda's prompt, if that's a problem.
you have a space between f and the string. Remove it and everything will work.
The syntax error points to the end of the string. If it pointed to the beginning of the string it would give you a better hint at the problem: after the f, which is interpreted as a variable in this case, a string is unexpected.
You need this:
a = 1
b = 2
test_str = f"{'The variable a is'} {a} {'and the variable b is '}{b}"
print(test_str)
Between the curly braces, string interpolation takes place. The variables for a and b are within two of the curly brace sets and hard-coded strings are within the other two.

Python regex error: missing ), unterminated subpattern at position 35 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have this regex pattern:
(?P<prefix>.*)(?<!\\)\((?P<words>.+)(?<!\\)\)(?P<postfix>.*)
This regex is supposed to match a string like this:
hello my (friend|enemy) nice to see you again
The prefix group should capture hello my.
The words group should capture friend|enemy.
The postfix group should capture nice to see you again
This regex also uses lookbehinds to check if ( and ) are escaped using \ in string. For example, these two samples should not be detected since there is a \ before ( and ):
hello my \(friend|enemy) nice to see you again
hello my (friend|enemy\) nice to see you again
This pattern works well when I check it using online websites but when I try to run in in python (I'm using python 3.7), it throws the following error:
re.error: missing ), unterminated subpattern at position 35
What is the problem?
Edit:
Here is how I use it in python:
pattern = "(?P<prefix>.*)(?<!\\)\((?P<words>.+)(?<!\\)\)(?P<postfix>.*)"
match = re.search(pattern, line)
#Md Narimani
as #erhumoro suggested in comments, instead of:
line = "hello my (friend|enemy) nice to see you again"
pattern = "(?P<prefix>.*)(?<!\\)\((?P<words>.+)(?<!\\)\)(?P<postfix>.*)"
match = re.search(pattern, line)
Do:
line = "hello my (friend|enemy) nice to see you again"
pattern = r"(?P<prefix>.*)(?<!\\)\((?P<words>.+)(?<!\\)\)(?P<postfix>.*)"
match = re.search(pattern, line)
It is because of problems with escaping characters.

i don't know how to fix this error, python3 syntax error 'def' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I want to solve this error.
i tried for almost half hours, but I couldn't find the answer..
This is my error
File "sampling_fun.py", line 71
def average(self) :
^
SyntaxError: invalid syntax
and full code
import csv
class fun :
def __init__(self, rowList, num) :
list = []
listLen = len(self.rowlist)-1
for i in range(listLen) :
list.append(self.rowList[i+1][num] # num = Header 1~4
def average(self) :
ave = sum(self.list)/self.lestLen
print("average : %0.2f" %ave)
return ave
testlist = cssRead('Data_2', 1)
test1 = fun(testlist, 1)
test1.average()
When you encounter such error, check the line before it.
You have a non-matching paranthesis, the closing brace for append is missing.
list.append(self.rowList[i+1][num])
def errors happen when python is not expecting a function definition. As #Siong Thye Goh notes, a missing ) is your issue. For the future, the only time python does not expect a function definition is after an incomplete code-block.
That can happen when you forget to close parentheses or brackets, but also when you forget to put a statement after a colon or don't indent correctly.
Rarely, it can happen due to incompatible space characters when copy-pasting from external sources.

Syntax error for the most basic Python code [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have just started learning python and it seems I am getting errors with one line of code
ERROR MESSAGE:
File "hello.py", line 2
print ‘hello world!’
^
SyntaxError: invalid syntax
FULL CODE
# coding: utf-8
print ‘hello world!’
I'm not really sure what could be going wrong in this one simple line
Use single quotes, to be specific ' instead of ’.
Try:
# coding: utf-8
print 'hello world!'
Python accepts either single ' or double " quotes for strings. On special multiline occasions you can use triple quote '''.
Python 3 requires parentheses after print:
print('hello world')

I am not able to run this Python program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
import random
for i in range(1,21):
print("%10d" %(random.randrange(1,7)),
if (i % 5 == 0):
print ("")
What is wrong in this code ?
I know basic python (almost), but i am not able to figure out what could be error in this program.
it is showing this error:
Syntax Error: invalid syntax at line 6 (if statement)
The fourth line is missing bracket .. Thanks all of you
You missed a right bracket )
print("%10d" %(random.randrange(1,7))),
would be correct
You're missing a ) before the last comma on line 4.
Your parenthesis on line 4 don't match. Because you have an unclosed paren, python doesn't report this syntax error until the colon on line 6 (python ignores line breaks as long as you are inside an enclosing set of parenthesis, brackets, or braces).

Categories