replace multi words using dictionary [closed] - python

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 6 years ago.
Improve this question
import re
dic={}
dic1={}
s="ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR `COUNTRY"
sentence=". ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU"
sentence0=". ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
sentence2=sentence.split()
sentence1=sentence.split()
for position,char in enumerate(sentence1):
dic[(char)]=(position)
for position,char in enumerate(sentence2):
dic1[(char)]=(position)
dic.update(dic1)
del dic["."]
print(dic)
pattern = re.compile(r'\b(' + '|'.join(dic.keys()) + r')\b')
result = pattern.sub(lambda x: dic[x.group()], s)
print(result)
When I run the program I have these error TypeError: sequence item 0: expected str instance, int found.How can I solve it?

You need a string for the sub function, to fix that you can either change the dictionary's values to strings:
dic1[(char)]=str(position)
or change the lambda function to:
result = pattern.sub(lambda x: str(dic[x.group()]), s)

Related

Coverting a python list into string with comma separated in efficient way [closed]

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 3 years ago.
Improve this question
I have a list of acc nos:
list1 = ['1234','3456','2345','5543','1344','5679','6433','3243','0089']
Output I need is a string:
print(output): '1234','3456','2345','5543','1344','5679','6433','3243','0089'
You can join all the values with ',' and then adding a ' before and after the string like this:
"'{0}'".format("','".join(list1))
>>> list1 = ['1234','3456','2345','5543','1344','5679','6433','3243','0089']
>>> print(','.join(["'{0}'".format(s) for s in list1]))
'1234','3456','2345','5543','1344','5679','6433','3243','0089'

Return part of string between specific character pair, in string with multiple character pairs [closed]

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 3 years ago.
Improve this question
Text file or string:
SomeText1/SomeText2/SomeText3/SomeText4/SomeText5
#What I am looking for:
split_func(3, "/")
>>> SomeText3
Try:
s = "SomeText1/SomeText2/SomeText3/SomeText4/SomeText5"
# s.split("/") returns a list of strings, split at the "/"
# I.e. ["SomeText1", "SomeText2", "SomeText3", "SomeText4", "SomeText5"]
# Then take the second element (remembering that the count starts at 0
result = s.split("/")[2]

select the characters in after "):" and print it in between? [closed]

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 3 years ago.
Improve this question
I have a file like this
(E:0.13228,((D:0.08440,A:0.14071):0.29270,(H:0.30329,(B:0.06928,
(F:0.00236,G:0.00010):0.00010):0.44531):0.06201):0.57269,C:0.19183);
I need to generate it as follows:
(E:0.13228,((D:0.08440,A:0.14071)0.29270:0.29270,(H:0.30329,(B:0.06928,
(F:0.00236,G:0.00010)0.00010:0.00010)0.44531:0.44531)0.06201:0.06201)0.57269:0.57269,C:0.19183);
What you should use in this cases are the regular expressions. Check Python re
match_pattern = r'\):(\d(\.\d+)?)'
output_pattern = r')\1:\1'
input_str = """(E:0.13228,((D:0.08440,A:0.14071):0.29270,(H:0.30329,(B:0.06928,
(F:0.00236,G:0.00010):0.00010):0.44531):0.06201):0.57269,C:0.19183);"""
output_str = re.sub(match_pattern, output_pattern, input_str)
print(output_str)
And the result is:
(E:0.13228,((D:0.08440,A:0.14071)0.29270:0.29270,(H:0.30329,(B:0.06928,
(F:0.00236,G:0.00010)0.00010:0.00010)0.44531:0.44531)0.06201:0.06201)0.57269:0.57269,C:0.19183);
I guess you could go with some string manipulation like so if you're not using regular expressions
data = "(E:0.13228,((D:0.08440,A:0.14071):0.29270,(H:0.30329,(B:0.06928,
(F:0.00236,G:0.00010):0.00010):0.44531):0.06201):0.57269,C:0.19183);"
dataParts = data.split("):")
correctedData = dataParts[0]
for dataPart in dataParts[1:]:
number = dataPart[:7]
correctedData = "){}:".format(number).join([correctedData, dataPart])
but that's not clean...

python format string by length [closed]

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 4 years ago.
Improve this question
I have some strings below:
123123|00|992|1111
222222|2222|19|922
997997|3333|922|77
How can I format like this (sort by len):
123123|1111|00|992
222222|2222|19|922
997997|3333|77|922
Using str.split & str.join with sorted
Demo:
s = """123123|00|992|1111
222222|2222|19|922
997997|3333|922|77"""
data = ["|".join(sorted(i.split("|"), key=len, reverse=True)) for i in s.split("\n")]
print( "\n".join(data) )
Output:
123123|1111|992|00
222222|2222|922|19
997997|3333|922|77
Try this
a='''123123|00|992|1111
222222|2222|19|922
997997|3333|922|77'''
'\n'.join(['|'.join(sorted(e.split("|"),key=len,reverse=True)) for e in a.split("\n")])
Output:
123123|1111|992|00
222222|2222|922|19
997997|3333|922|77
The OPs sort order isn't based on string length, as the length of 2 comes before the length of 3 (the very last two segments)
for that purpose, a custom sort mapping is needed
ranks = {6:0, 4:1, 2:2, 3:3}
text = """123123|00|992|1111
222222|2222|19|922
997997|3333|922|77"""
result = '\n'.join(['|'.join(sorted(line.split('|'),key=lambda x: ranks[len(x)]))
for line in text.split('\n')])
print(result)
# outputs:
123123|1111|00|992
222222|2222|19|922
997997|3333|77|922

How to replace a dot with a string in a python list [closed]

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 6 years ago.
Improve this question
my_list = ['b','.','.']
expected_list = ['b','.','w']
May be simple, moving into python recently so any suggestions would be fine
You can do this by using list comprehension also
l = ['w' if i == '.' else i for i in my_list]
If you are replacing every occurrence of '.' with 'w' then I would just suggest:
for n, i in enumerate(my_list):
if i == '.':
my_list[n] = 'w'
Here is the documentation for how to use the enumerate() function: https://docs.python.org/2/library/functions.html#enumerate

Categories