Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The simulation code I use needs to read parameters from an input.txt file which looks like
paramA = 1,paramB = 2,
paramC = 3,paramD = 4,
When scanning a parameter (like paramC) in my simulation, I need to change the value of paramC every time manually. How can I do this with a perl script so that when I type
perl scriptname input.txt paramC 100
in the command line I can get a modified input file with paramC changed to 100
paramA = 1,paramB = 2,
paramC = 100,paramD = 4,
I can do this by creating a template file like
paramA = 1,paramB = 2,
paramC = <>,paramD = 4,
and then use perl to match the mark <> and replace it with the value I want. However is there a more direct way to match the parameter name and change its value ?
thanks.
The obvious answer is to use a regular expression. Perl is quite good at those.
So you could - for example - do:
s/paramC = \d+/paramC = $value/g;
Which'll do the trick I'd have thought?
Edit: Or use TLP's pattern in the comments:
s/^paramC = \K[^ ,]+/$value/g;
or perhaps:
s/^paramC = \K\d+/$value/g;
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am getting values from an api call and it returns one json value/key pair as a string at a time. I need to count how many times items with a certain prefix (which encodes the type of the item) occur:
Lets say I am getting 'abc123' as the 1st value
def getType(nodeName):
nodeCount = 0
if "abc" in nodeName:
count = count + 1
return "ABC", count
How do I retain this nodeCount value so that next time an item with prefix 'abc' comes in from the api call, the count can be incremented to 2.
Also, I need to create other counters to keep track of the count of other node types, such as 'xyz777'.
I tried to declare nodeCount as global variable but if I add "global count", that will defeat the purpose of retaining the count value for the next api call/iteration.
I am very new to python, so please let me know if there is any easy way.
Many Thanks!
You may use a collections.Counter like this:
from collections import Counter
def getType(counter, nodeName):
nodetype= nodeName.rstrip('0123456789')
counter[nodetype] += 1
return nodetype.upper(), counter[nodetype]
c= Counter()
for n in ['abc123', 'def789', 'ghijk11', 'def99', 'abc444']:
nodetype, nodecount = getType(counter= c, nodeName= n)
print('type {} \t: {}'.format(nodetype, nodecount))
print('summary:')
print(c)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a string having the following format:
ip = 192.168.1.2
user = test
password = test0
ip =, user = and password = are fixed but the strings to the right of the equals signs may vary.
Using Perl, I would like to write a one-line command to replace the string following user = with a given string, say, X, to return the following new string:
ip = 192.168.1.2
user = X
password = test0
Thanks for your help.
$ perl -p -e 's/^user =.*/user = X/' file
ip = 192.168.1.2
user = X
password = test0
If you want the string to substitute to be configurable, you can use the following:
$ user=X
$ perl -spe's/^user =\K.*/ $user/' -- -user="$user" file
ip = 192.168.1.2
user = X
password = test0
See Specifying file to process to Perl one-liner.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
CONFIG.CONFIG
create state file${number_of_edges} {
{interval=60
idle_interval_notification="DISABLED"}
}
create state file${number_of_edges} {
{interval=60
idle_interval_notification="DISABLED"}
}
I have file which has content like above. I want to replace ${number_of_edges} string with consecutive numbers like 0,1,2 and so on
EXPECTED OUTPUT
create state file0 {
{interval=60
idle_interval_notification="DISABLED"}
}
create state file1{
{interval=60
idle_interval_notification="DISABLED"}
}
create state file2 {
{interval=60
idle_interval_notification="DISABLED"}
}
I got the solution.
Command -
awk -vRS=edge '{$0=n$0;ORS=RT}++n' FILE
A simple awk script:
awk 'sub("\\${number_of_edges}",cnt+1, $0){cnt++}1' input.txt
Explanation:
sub("\\${number_of_edges}",cnt+1, $0) For each input line, substitute, ${number_of_edges} with variable (cnt + 1)
{cnt++} If substituted more than 0, increment variable cnt
1 output each input line
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my R code, I have the following content of x as a result of lda prediction output.
[1] lamb
Levels: lamb cow chicken
I would like to capture the word "lamb" in the first line and not the second line.
I had the following reg expression which did not work.
if (regmatches(x,regexec(".*?([a-z]+)",x))[[1]][2]=="lamb"){
cat("It is a lamb")
}
Instead, I also got the following error :-
Error in regexec(".*?([a-z]+)", x) : invalid 'text' argument
Anyone with help ?
Thanks in advance.
mf
Direct Answer:
It is a variable type error. See ?predict.lda to learn why: The return object of a predict() when used with an object of class lda is a list. You just want the first element of the list, which is a factor for an object of type integer. Factors in R store some characters for every element in their level component, which can be accessed by levels() (Read ?factor as well.). But what you want is to access the explicit value your factor shows, which can be acheived by as.character(). By the way: The second line does not get checked by the regex. It is just standard console output of a factor, see ?print.factor.
Here's an example, based on thepredict.lda() help page:
tr <- sample(1:50, 25)
train <- rbind(iris3[tr,,1], iris3[tr,,2], iris3[tr,,3])
test <- rbind(iris3[-tr,,1], iris3[-tr,,2], iris3[-tr,,3])
cl <- factor(c(rep("s",25), rep("c",25), rep("v",25)))
z <- lda(train, cl)
x_lda <- predict(z, test)
# x_lda is a list
typeof(x_lda)
# The first element of the list, called "class", is a factor of type integer.
typeof(x_lda$class)
# Now we create a character vector from the factor:
as.character(x_lda$class)
With an explicit character object, your code works for me:
x <- "lamb"
regmatches(x,regexec(".*?([a-z]+)",x))[[1]][2]=="lamb"
[1] TRUE
So you need to coerce your object to character, and then use it as the "text" argument for the regexec function.
Actual Answer:
There are better ways to do this.
You nest and chain a lot of functions in one line. This is barely readable and makes debugging hard.
If you know that the output will always consist of certain elements (especially, since you know the input of your lda prediction and therefore know the different factor levels beforehand), you can simply check them by == and maybe any() (continuing with the example from before):
levels(cl)
[1] "c" "s" "v"
any(as.character(x_lda$class)=="c")
[1] TRUE
See the help file for ?any, if you don't know what it does.
Finally, if you just want to print "It is a lamb" in the end, and your output will always just have one element, you can simply use paste():
paste("It is a", as.character(x))
[1] "It is a lamb"
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Hannuka, Chanukah, Hanukkah...Due to transliteration from another language and character set, there are many ways to spell the name of this holiday. How many legitimate spellings can you come up with?
Now, write a regular expression that will recognise all of them.
According to http://www.holidays.net/chanukah/spelling.htm, it can be spelled any of the following ways:
Chanuka
Chanukah
Chanukkah
Channukah
Hanukah
Hannukah
Hanukkah
Hanuka
Hanukka
Hanaka
Haneka
Hanika
Khanukkah
Here is my regex that matches all of them:
/(Ch|H|Kh)ann?[aeiu]kk?ah?/
Edit: Or this, without branches:
/[CHK]h?ann?[aeiu]kk?ah?/
Call me a sucker for readability.
In Python:
def find_hanukkah(s):
import re
spellings = ['hannukah', 'channukah', 'hanukkah'] # etc...
for m in re.finditer('|'.join(spellings), s, re.I):
print m.group()
find_hanukkah("Hannukah Channukah, Hanukkah")
Something like C?hann?uk?kah? matches most of the common cases. There also a bunch of weirder spellings C?hann?uk?kah?|Han[aei]ka|Khanukkah matches almost every spelling I could think of (that had at least half a million hits on google).
((Ch|H|X|Х|Kh|J)[aа](н|n{1,2})(у|ou|[auei])(к|k|q){1,2}[aа]h?)|(חנו?כה)
This regex is much more inclusive and covers all of the following options:
Channuka
Channukah
Channukka
Channukkah
Chanuka
Chanukah
Chanukah
Chanukka
Chanukkah
Chanuqa
Hanaka
Haneka
Hanika
Hannuka
Hannukah
Hannukka
Hannukkah
Hanoukka
Hanuka
Hanukah
Hanukka
Hanukkah
Januka
Khanukkah
Xanuka
Ханука
Ханука
חנוכה
חנכה
Try this:
/^[ck]?hann?ukk?ah?$/i
I think the only approved spellings in English are Hanukkah and Chanukh, so it's something like
/(Ch|H)anuk?kah/
Or maybe even better
/(Chanukah|Hanukkah)/
I like Triptych's answer, but i would take it one step forward... also in python:
def valid(spelling):
import re
regex_spelling = re.compile(r'^[cCkK]{0,1}han{1,2}uk{1,2}ah$')
valid = regex_spelling.match(spelling)
if valid:
print 'Valid spelling'
else:
print spelling, " is not a spelling for the word"
to use it:
valid("hanukkah")