This is so far what has been my progress with this regex function :
import os, re
dpath="/root/tree/def/"
fmatch = re.compile(r'\s+''[\[]+''[A-Z]+''[\]]+')
pmatch = fmatch.match('[FLAC]')
def replace(pmatch,df):
m = re.sub(fmatch,df)
print (m)
def regex(dpath):
for df in os.listdir(dpath):
replace(pmatch, df)
regex (dpath)
First do a for loop and look for files in (dpath), then pass the directory name string to replace(). But I am getting missing argument 'string' error :
root#debian:~# python regex3.py
Traceback (most recent call last):
File "regex3.py", line 18, in <module>
regex (dpath)
File "regex3.py", line 16, in regex
replace(pmatch, df)
File "regex3.py", line 9, in replace
m = re.sub(fmatch,df)
TypeError: sub() missing 1 required positional argument: 'string'
It seems that you want to replace alls all matches of the RegEx \s+[\[]+[A-Z]+[\]]+ to [FLAC]
Make sure you do the following:
def replace(pmatch,df):
m = fmatch.sub('[FLAC]', df)
print (m)
Using #martin-konecny 's Example,
I got this that worked.
Create Files for Example
# Run this in your Shell/Terminal
touch /tmp/abc.FLAC
touch /tmp/abcd.FLAC
Run Python
import re
import os
dpath = '/tmp/'
fmatch = re.compile(r'.+\.FLAC')
pmatch = fmatch.match('[FLAC]')
def replace(pmatch, df):
m = fmatch.sub('[REDACTED]', df)
print(m)
def regex(dpath):
for df in os.listdir(dpath):
replace(pmatch, df)
regex(dpath)
Result:
# ...
# [REDACTED]
# [REDACTED]
# ...
Great if you want to run a search and keep a selection of your results secret.
Related
i'm getting NameError: for the following code...
d = [('1','as'),('2','sd')]
for i in d:
RD = ReleaseDeal(int(i[0]))
print(RD)
def ReleaseDeal(a):
RD = '''<ReleaseDeal><DealReleaseReference>R'''+ no +'''</DealReleaseReference><Deal><DealTerms><CommercialModelType>AsPerContract</CommercialModelType>
<Usage><UseType UserDefinedValue="GoogleMusicBasic">UserDefined</UseType> <UseType UserDefinedValue="SscSnmLocker">UserDefined</UseType>
<UseType UserDefinedValue="GoogleMusicSubscription">UserDefined</UseType></Usage><TerritoryCode>Worldwide</TerritoryCode><PriceInformation>
<PriceType Namespace="DPID:"">13</PriceType></PriceInformation><ValidityPeriod><StartDate>2018-10-04</StartDate></ValidityPeriod>
</DealTerms></Deal></ReleaseDeal>'''
return RD
i'm getting following errors...
Traceback (most recent call last):
File "example.py", line 3, in <module>
RD = ReleaseDeal(int(i[0]))
NameError: name 'ReleaseDeal' is not defined
please help me on this , Thanks in advance..
You got several errors:
Define something before you reference to it
The parameter does not apply to the used one in ReleaseDeal
Concatenation of int to string fails.
def ReleaseDeal(no): # this was a, is has to be no and string
RD = '''<ReleaseDeal><DealReleaseReference>R'''+ no +'''</DealReleaseReference><Deal><DealTerms><CommercialModelType>AsPerContract</CommercialModelType>
<Usage><UseType UserDefinedValue="GoogleMusicBasic">UserDefined</UseType> <UseType UserDefinedValue="SscSnmLocker">UserDefined</UseType>
<UseType UserDefinedValue="GoogleMusicSubscription">UserDefined</UseType></Usage><TerritoryCode>Worldwide</TerritoryCode><PriceInformation>
<PriceType Namespace="DPID:"">13</PriceType></PriceInformation><ValidityPeriod><StartDate>2018-10-04</StartDate></ValidityPeriod>
</DealTerms></Deal></ReleaseDeal>'''
return RD
d = [('1','as'),('2','sd')]
for i in d:
RD = ReleaseDeal(i[0])
print(RD)
Maybe type hints are useful for you ;-) https://docs.python.org/3/library/typing.html#typing.ClassVar Then you can say something like
ReleaseDeal(no: str) -> str:
So you want to get no of type string and return string.
Hi I'm VERY new to programming, and I am working on my first program. I've been following along in a book and I decided to stop and test a function. The function is in a file called myPythonFunctions.py. I then created a new file called untitled.py and put it in the same folder as myPythonFunctions.py.
In untitled.py I have the following code:
import myPythonFunctions as m
m.generateQuestion()
Very simple, but when I try to run it I get Import Error: no module named myPythonFunctions.
I don't understand, there is clearly a file named myPythonFunctions in the folder. What's going on?
In case you need it, here is the code for m.generateQuestion()
def generateQuestion():
operandList = [0,0,0,0,0,]
operatorList = ['', '', '', '', '']
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
for index in range(0,5):
operandList[index] = randint(1,9)
for index in range(0,4):
if index > 0 and operatorList[index-1] !='**':
operator = operatorDict[randint(1,4)]
else:
operator = operatorDict[randint(1,3)]
operatorList[index] = operator
questionString = str(operandList[0])
for index in range(1,5):
questionString = questionString + OperatorList[index-1] + str[operandList[index]
result = eval(questionString)
questionString.replace("**","^")
print('\n' + questionString)
userAnswer=input('Answer: ')
while true:
try:
if int(userAnswer) == result:
print('Correct!')
return 1
else:
print('Sorry, the correct answer is', result)
return 0
except Exception as e:
print("That wasn't a number")
userAnswer = input('Answer: ')
Edit: I'm now getting this error
Traceback (most recent call last):
File "/Users/Brad/Desktop/Python/Untitled.py", line 1, in <module>
import myPythonFunctions as m
File "/Users/Brad/Desktop/Python/myPythonFunctions.py", line 33
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
^
SyntaxError: invalid syntax
The syntaxis error you are getting, is because you are trying to define a dictionary as a list, so the interpreter is raising the error because it does not know what to do with that.
To define a dictionary you need to use { } instead of [ ]
--- EDIT 2
Your dictionary implementation is wrong, do you really copied this code from somewhere?
The
operatorDict = {1:'+', 2:'-', 3:'*', 4:'**'}
Your code was mispelled
---- EDIT
Your code on myPythonFunctions is really bad.
Python needs correct identation to works, please double check this step
I suggest you to do a check in your structure:
I did this right now
/somefolder
--this.py
--functions.py
/
The contents
--this.py
import functions as f
print f.hello()
--functions.py
def hello():
return 'It worked'
Try this structure in your environment :D
And then run:
python this.py
As a part of schoolwork we have been given this code:
>>> IN = re.compile(r'.*\bin\b(?!\b.+ing)')
>>> for doc in nltk.corpus.ieer.parsed_docs('NYT_19980315'):
... for rel in nltk.sem.extract_rels('ORG', 'LOC', doc,
... corpus='ieer', pattern = IN):
... print(nltk.sem.rtuple(rel))
We are asked to try it out with some sentences of our own to see the output, so for this i decided to define a function:
def extract(sentence):
import re
import nltk
IN = re.compile(r'.*\bin\b(?!\b.+ing)')
for rel in nltk.sem.extract_rels('ORG', 'LOC', sentence, corpus='ieer', pattern = IN):
print(nltk.sem.rtuple(rel))
When I try and run this code:
>>> from extract import extract
>>> extract("The Whitehouse in Washington")
I get the gollowing error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
extract("The Whitehouse in Washington")
File "C:/Python34/My Scripts\extract.py", line 6, in extract
for rel in nltk.sem.extract_rels('ORG', 'LOC', sentence, corpus='ieer', pattern = IN):
File "C:\Python34\lib\site-packages\nltk\sem\relextract.py", line 216, in extract_rels
pairs = tree2semi_rel(doc.text) + tree2semi_rel(doc.headline)
AttributeError: 'str' object has no attribute 'text'
Can anyone help me understand where I am going wrong in my function?
The correct output for the test sentence should be:
[ORG: 'Whitehouse'] 'in' [LOC: 'Washington']
If you see the method definition of extract_rels, it expects the parsed document as third argument.
And here you are passing the sentence. To overcome this error, you can do following :
tagged_sentences = [ nltk.pos_tag(token) for token in tokens]
class doc():
pass
IN = re.compile(r'.*\bin\b(?!\b.+ing)')
doc.headline=["test headline for sentence"]
for i,sent in enumerate(tagged_sentences):
doc.text = nltk.ne_chunk(sent)
for rel in nltk.sem.relextract.extract_rels('ORG', 'LOC', doc, corpus='ieer', pattern=IN):
print(nltk.sem.rtuple(rel) )// you can change it according
Try it out..!!!
I have the following code that uses 3 strings 'us dollars','euro', '02-11-2014',
and a number to calculate the exchange rate for that given date. I modified the
code to pass those arguments but I get an error when I try to call it with
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
Traceback (most recent call last):
File "currencyManager.py", line 37. in <module>
currencyManager(currTo,currFrom,currAmount,currDate)
NameError: name 'currTo' is not defined
I'm fairly new to Python so my knowledge is limited. Any help would be greatly appreciated. Thanks.
Also the version of Python I'm using is 3.4.2.
import urllib.request
import re
def currencyManager(currTo,currFrom,currAmount,currDate):
try:
currency_to = currTo #'us dollars'
currency_from = currFrom #'euro'
currency_from_amount = currAmount
on_date = currDate # Day-Month-Year
currency_from = currency_from.replace(' ', '+')
currency_to = currency_to.replace(' ', '+')
url = 'http://www.wolframalpha.com/input/?i=' + str(currency_from_amount) + '+' + str(currency_from) + '+to+' + str(currency_to) + '+on+' + str(on_date)
req = urllib.request.Request(url)
output = ''
urllib.request.urlopen(req)
page_fetch = urllib.request.urlopen(req)
output = page_fetch.read().decode('utf-8')
search = '<area shape="rect.*href="\/input\/\?i=(.*?)\+.*?&lk=1'
result = re.findall(r'' + search, output, re.S)
if len(result) > 0:
amount = float(result[0])
print(str(amount))
else:
print('No match found')
except URLError as e:
print(e)
currencyManager(currTo,currFrom,currAmount,currDate)
The command line
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
does not automatically assign "us dollars" "euro" 100 "02-11-2014" to currTo,currFrom,currAmount,currDate.
Instead the command line arguments are stored in a list, sys.argv.
You need to parse sys.argv and/or pass its values on to the call to currencyManager:
For example, change
currencyManager(currTo,currFrom,currAmount,currDate)
to
import sys
currencyManager(*sys.argv[1:5])
The first element in sys.argv is the script name. Thus sys.argv[1:5] consists of the next 4 arguments after the script name (assuming 4 arguments were entered on the command line.) You may want to check that the right number of arguments are passed on the command line and that they are of the right type. The argparse module can help you here.
The * in *sys.argv[1:5] unpacks the list sys.argv[1:5] and passes the items in the list as arguments to the function currencyManager.
I am creating a .png barcode from an alpha numerical value. I am using Python and the pyBarcode module. The problem is that, when I use code39, it adds a random digit to the end. Other barcode formats I tested seems to give the same problem.
Here is my code snippet
unique_filename = uuid.uuid4()
barcode_writer = ImageWriter()
ean = barcode.get('code39', "Testing-One-two-1-2",barcode_writer)
filename = ean.save(BARCODE_DIR +str(unique_filename))
And the created .png:
Non-OP Edit: Link to image is now broken.
Hope someone can assist me.
Thanks
Looking at the source code for pyBarcode init function on line 57 the barcode.get() function calls:
return barcode(code, writer)
So it creates a barcode with the parameters code and writer set.
In the codex.py file on line 52, the code39 class is created with the checksum parameter True by default:
def __init__(self, code, writer=None, add_checksum=True):
And as per lnmx you have to explicitly set the checksum off if you don't want it.
Peter M is right, the extra character is a checksum. You can omit it by specifying add_checksum=False:
ean = barcode.get('code39', "Testing-One-two-1-2", barcode_writer, add_checksum=False)
ref: http://pythonhosted.org/pyBarcode/barcode.html
I tried using the parameter 'add_checksum=False' with 'barcode.get()' and it raised an error:
barcode_writer = ImageWriter()
ean = barcode.get('code39', "Testing-One-two-1-2",barcode_writer, add_checksum=False)
TypeError Traceback (most recent call
last) in ()
1 barcode_writer = ImageWriter()
----> 2 ean = barcode.get('code39', "Testing-One-two-1-2",barcode_writer, add_checksum=False)
TypeError: get() got an unexpected keyword argument 'add_checksum'
So I found on module reference page (https://pythonhosted.org/pyBarcode/codes.html) that you can specify the type of barcode, using it as a class and then you can provide the paramenter 'add_checksum=False'.
barcode_writer = ImageWriter()
ean = barcode.codex.Code39( "Testing-One-two-1-2", barcode_writer, add_checksum=False)
unique_filename = uuid.uuid4()
filename = ean.save(unique_filename)