How to get hex value according to skinid - python

I want to find and get hex value keyword from SkinId input.
Download example file for read by myself : Example file
import re, os
os.system('color 4')
def find_keyword(skinId):
with open("infos/116_JingKe_actorinfo.bytes", "rb") as f:
byte_string = f.read()
key_word = f"116_JingKe/{skinId}".encode('utf-8')
#key_word = b'TypeSystem.String'
matches = re.findall(key_word, byte_string)
start_keyword = b'JTPri'
end_keyword = b'LOD'
# Define the regular expression pattern to match the start and end keywords
#pattern = re.compile(start_keyword + b".*?" + end_keyword + b"\d*", re.DOTALL)
#pattern = re.compile(start_keyword + b".*?(?=LOD|Show\d)", re.DOTALL)
pattern = re.compile(start_keyword + b".*?(?=LOD|Show)" + end_keyword + b"\d*", re.DOTALL)
#pattern = re.compile(start_keyword + b".*?" + end_keyword, re.DOTALL)
# Find all occurrences of the pattern in the file contents
matches = pattern.findall(byte_string)
for match in matches:
if key_word in match:
print(match)
while True:
skinId = input(" >>> SKIN ID :")
find_keyword(skinId)
if skinId == 'x':
break
os.system('pause')
os.system('cls')
Result : https://i.stack.imgur.com/zOGNL.png
Desired result :
b'JTPri\x19\x00\x00\x00\x08\x00\x00\x00TypeSystem.StringC\x00\x00\x00\x05\x00\x00\x00VPrefab_Characters/Prefab_Hero/116_JingKe/11614_JingKe_LOD1'
b'JTPri\x19\x00\x00\x00\x08\x00\x00\x00TypeSystem.StringC\x00\x00\x00\x05\x00\x00\x00VPrefab_Characters/Prefab_Hero/116_JingKe/11614_JingKe_LOD2'
b'JTPri\x19\x00\x00\x00\x08\x00\x00\x00TypeSystem.StringC\x00\x00\x00\x05\x00\x00\x00VPrefab_Characters/Prefab_Hero/116_JingKe/11614_JingKe_LOD3'
b'JTPri\x19\x00\x00\x00\x08\x00\x00\x00TypeSystem.StringD\x00\x00\x00\x05\x00\x00\x00VPrefab_Characters/Prefab_Hero/116_JingKe/11614_JingKe_Show1
b'JTPri\x19\x00\x00\x00\x08\x00\x00\x00TypeSystem.StringD\x00\x00\x00\x05\x00\x00\x00VPrefab_Characters/Prefab_Hero/116_JingKe/11614_JingKe_Show2'
b'JTPri\x19\x00\x00\x00\x08\x00\x00\x00TypeSystem.StringD\x00\x00\x00\x05\x00\x00\x00VPrefab_Characters/Prefab_Hero/116_JingKe/11614_JingKe_Show3'

Related

Find and replace in string re.insensitive

I have this code to find matches in a string, im using in a search to mark the wordds that match my search, i need this to be case insensitive, the issue here is that it replaces the word by the one we search.
val_to_searchp = "this Text string has alot of teXt"
word = "TEXT"
pal2rep = str(":::")+word+str(":::")
val_to_search = re.sub(re.escape(word), pal2rep, val_to_searchp, flags=re.IGNORECASE)
this will return
"this :::TEXT::: string has alot of :::TEXT:::"
I need it to return
"this :::Text::: string has alot of :::teXt:::"
Also tryed with this but its not working very well :(
f = 0
s = 0
val_to_search = val_to_searchp
for m in re.finditer(str(word), str(val_to_searchp)):
inicio = int(m.start()+s)
fim = int(m.end()+f)
val_to_search = val_to_search[:inicio] \
+ str(":::") \
+ val_to_search[inicio:fim] \
+ str(":::") \
+ val_to_search[fim:].strip()
f = f+2
s = s+1
This is my actuall code
def findtext():
if len(str(findtext_inp.get('1.0', END)))>1:
val_to_searchp = str(respon_txt.get(1.0, END).replace(html.unescape('⛔'), "").strip())
respon_txt.delete(1.0, END)
word = str(findtext_inp.get('1.0', END).strip())
pal2rep = str(str(html.unescape('⛔'))+word+str(html.unescape('⛔')))
val_to_search = re.sub(re.escape(word), pal2rep, val_to_searchp, flags=re.IGNORECASE)
"""
f = 0
s = 0
for m in re.finditer(str(word), str(val_to_search)):
inicio = int(m.start()+s)
fim = int(m.end()+f)
val_to_search = val_to_search[:inicio] \
+ str(html.unescape('⛔')) \
+ val_to_search[inicio:fim] \
+ str(html.unescape('⛔')) \
+ val_to_search[fim:].strip()
f = f+2
s = s+1
"""
respon_txt.insert(1.0, val_to_search)#val_to_search.replace(findtext_inp.get('1.0', END).strip() , str(html.unescape('⛔')+findtext_inp.get('1.0', END).strip())+html.unescape('⛔')))
I'm sure there's a way to do this with RE but it's really trivial without the aid of that module.
val_to_searchp = "this Text string has alot of teXt\nThis also has a lot of text"
text = 'TEXT'
def func(s, txt):
txt = txt.lower()
result = []
for line in s.split('\n'):
for i, e in enumerate(t := line.split()):
if e.lower() == txt:
t[i] = f':::{e}:::'
result.append(' '.join(t))
return '\n'.join(result)
print(func(val_to_searchp, text))
Output:
this :::Text::: string has alot of :::teXt:::
This also has a lot of :::text:::
This is a rewrite of my original answer. In the comments for that answer you will see that the OP has changed his mind about how this needs to work. This now (hopefully) complies with the altered specification:
val_to_searchp = '''{\"configurationKey\":[{\"key\":\"GetMaxKeys\",\"readonly\":true,\"value\":\"20\"}'''
text = 'GetMaxKeys'
def func(s, txt):
result = []
sl = s.lower()
txt = txt.lower()
lt = len(txt)
offset = 0
while (i := sl[offset:].find(txt)) >= 0:
result.append(s[offset:i+offset])
offset += i
result.append(f':::{s[offset:offset+lt]}:::')
offset += lt
result.append(s[offset:])
return ''.join(result)
print(func(val_to_searchp, text))
Output:
{"configurationKey":[{"key":":::GetMaxKeys:::","readonly":true,"value":"20"}

Python 2.7 split and .col concatenate

I am using python 2.7 version.
I am trying to extract array column name using python.
Array column is mentioned below:
`col` array<struct< columnname:string,columnname1:int,columnname2:decimal(10,0),
columnname3:decimal(9,2)>>
What I tried so far:
import re
str=input("enter any string:")
fields=str.split(",")
for x in fields:
name=x.split(":")
seminame=name[0]+','
firstname=seminame.find('`')
lastname=seminame.rfind('`')
fullname=seminame[(firstname+1):lastname]
replacename1=fullname.replace(')', '')
replacename2=fullname.replace('2', '')
replacename3=fullname.replace('9', '')
replacename4=fullname.replace('10', '')
replacename5=fullname.replace('0', '')
finalname='.'+replacename5
print(finalname)
Input:
'`col` array<struct< columnname:string,columnname1:int,columnname2:decimal(10,0),
columnname3:decimal(9,2)>>'
I want the output as
Actual output
.col,
.columnname1,
.columnname2,
.),
Expected output
col.columnname,
col.columnname1,
col.columnname2,
col.columnname3
Why not use re to do the same?
import re
str = "'`col` array<struct< columnname:string,columnname1:int,columnname2:decimal(10,0),columnname3:decimal(9,2)>>'"
word = re.findall("`\w+`",str,) # match for columns
word = " ".join(word)
word = re.sub(r'\W+', '', word) # strip ``
columnnames = re.findall(r"(\w+):",str) # find all words before `:`
for c in columnnames:
c = re.sub(r'\W+', '', c) # to remove `:`
print "%s.%s," %( word,c)
Output :
col.columnname,
col.columnname1,
col.columnname2,
col.columnname3,
To read from file you can use open(filename,mode) method
import re
with open("test.txt","r") as h:
str = h.read()
word = re.findall(r"`\w+`",str,)
word = " ".join(word)
word = re.sub(r'\W+', '', word)
columnnames = re.findall(r"(\w+):",str)
for c in columnnames:
c = re.sub(r'\W+', '', c)
print "%s.%s," %( word,c)
To Write to File:
import re
with open("test.txt","r") as h:
with open("output.dat","a") as w:
str = h.read()
word = re.findall(r"`\w+`",str,)
word = " ".join(word)
word = re.sub(r'\W+', '', word)
columnnames = re.findall(r"(\w+):",str)
for c in columnnames:
c = re.sub(r'\W+', '', c)
data = "%s.%s," %( word,c)
w.write(data+"\n")
w.close()
h.close()

Python : How to translate?

the program is when user input"8#15#23###23#1#19###9#20"
output should be "HOW WAS IT"
However,it could not work to show space(###).
enter code here
ABSTRACT ={"A":"1","B":"2","C":"3","D":"4","E":"5","F":"6","G":"7","H":"8","I":"9", "J":"10","K":"11","L":"12","M":"13","N":"14","O":"15","P":"16","Q":"17","R":"18","S":"19","T":"20","U":"21","V":"22","W":"23", "X":"24","Y":"25","Z":"26",
" ":"###","":"#" }
ABSTRACT_SHIFTED = {value:key for key,value in ABSTRACT.items()}
def from_abstract(s):
result = ''
for word in s.split('*'):
result = result +ABSTRACT_SHIFTED.get(word)
return result
This would do the trick:
#!/usr/bin/env python
InputString = "8#15#23###23#1#19###9#20"
InputString = InputString.replace("###", "##")
InputString = InputString.split("#")
DecodedMessage = ""
for NumericRepresentation in InputString:
if NumericRepresentation == "":
NumericRepresentation = " "
DecodedMessage += NumericRepresentation
continue
else:
DecodedMessage += chr(int(NumericRepresentation) + 64)
print(DecodedMessage)
Prints:
HOW WAS IT
you can also use a regex
import re
replacer ={"A":"1","B":"2","C":"3","D":"4","E":"5","F":"6","G":"7","H":"8","I":"9", "J":"10","K":"11","L":"12","M":"13","N":"14","O":"15","P":"16","Q":"17","R":"18","S":"19","T":"20","U":"21","V":"22","W":"23", "X":"24","Y":"25","Z":"26",
" ":"###","":"#" }
reversed = {value:key for key,value in replacer.items()}
# Reversed because regex is greedy and it will match 1 before 15
target = '8#15#23###23#1#19###9#20'
pattern = '|'.join(map(lambda x: x + '+', list(reversed.keys())[::-1]))
repl = lambda x: reversed[x.group(0)]
print(re.sub(pattern, string=target, repl=repl))
And prints:
HOW WAS IT
With a couple minimal changes to your code it works.
1) split on '#', not '*'
2) retrieve ' ' by default if a match isn't found
3) use '##' instead of '###'
def from_abstract(s):
result = ''
for word in s.replace('###','##').split('#'):
result = result +ABSTRACT_SHIFTED.get(word," ")
return result
Swap the key-value pairs of ABSTRACT and use simple split + join on input
ip = "8#15#23###23#1#19###9#20"
ABSTRACT = dict((v,k) for k,v in ABSTRACT.items())
''.join(ABSTRACT.get(i,' ') for i in ip.split('#')).replace(' ', ' ')
#'HOW WAS IT'
The biggest challenge here is that "#" is used as a token separator and as the space character, you have to know the context to tell which you've got at any given time, and that makes it difficult to simply split the string. So write a simple parser. This one will accept anything as the first character in a token and then grab everything until it sees the next "#".
ABSTRACT ={"A":"1","B":"2","C":"3","D":"4","E":"5","F":"6","G":"7","H":"8","I":"9", "J":"10","K":"11","L":"12","M":"13","N":"14","O":"15","P":"16","Q":"17","R":"18","S":"19","T":"20","U":"21","V":"22","W":"23", "X":"24","Y":"25","Z":"26",
" ":"###","":"#" }
ABSTRACT_SHIFTED = {value:key for key,value in ABSTRACT.items()}
user_input = "8#15#23###23#1#19###9#20"
def from_abstract(s):
result = []
while s:
print 'try', s
# tokens are terminated with #
idx = s.find("#")
# ...except at end of line
if idx == -1:
idx = len(s) - 1
token = s[:idx]
s = s[idx+1:]
result.append(ABSTRACT_SHIFTED.get(token, ' '))
return ''.join(result)
print from_abstract(user_input)

substitute only some numbers by their decrement

I have this string: a9*a9 + a10*a10
and I would like to have: a9*a8 + a10*a9
I think re.sub() from Python should be useful, but I am not familiar with group() that I've seen in some examples. Any help would be appreciated.
here's another solution method:
import re
s = 'a9*a9 + a10*a10 + a8*a8 + a255*a255 + b58*b58 + c58*c58'
string = re.sub('[ ]', '', s) # removed whitespace from string (optional:only if you are not sure how many space you can get in string)
x = string.split('+')
pattern = re.compile(r'([a-z])([\d]+)')
ans = ''
for element in x:
for letter, num in re.findall(pattern, element):
st = ''
for i in range(len(element.split('*'))):
st = st + '*' + (letter+str(int(num)-i))
# print(str(letter) + str(int(num)-i))
ans = ans + '+' + st[1:]
print(ans[1:])
Output :
a9*a8+a10*a9+a8*a7+a255*a254+b58*b57+c58*c57
Assuming the structure of the input is a\d*a\d + a\d*a\d + ... you can use a callback in the re.sub function:
import re
def decrement(match):
if match.group(1) != match.group(2):
return match.group(0)
return 'a{}*a{}'.format(match.group(1), str(int(match.group(2)) - 1))
re.sub(r'a(\d)\*a(\d)', decrement, 'a3*a3 + a5*a5 + a3*a7')
# a3*a2 + a5*a4 + a3*a7

Splitting a string error: SyntaxError: can't assign to operator

I'm pulling address from my site because I didn't make a backup in xml format. I got it working, except now I want to divide the city and the country by the comma.
Here is what I have so far
#!/usr/bin/env python2.7
from requests import get
from bs4 import BeautifulSoup as Soup
f = open('scraped.csv', 'wb')
f.write('"Name","URL","Address Line 1","new_line1","new_line2","Phone"\n')
rej = open('rejected.csv', 'wb')
rej.write('"ID"\n')
for i in xrange(1, 7397 + 1):
try:
url = "http://map.crossfit.com/affinfo.php?a={}&t=0".format(i)
text = get(url).text
splitted = [foo.replace('\n', ' ') for foo in text.split('<br />')]
soup = Soup(splitted[0])
_, addr1, new_line1 = line1.split(',')[0], new_line2 = line1.split(',')[1] + ', ' + line2, phone = [foo.replace('"', '""') for foo in splitted]
name = soup.text
url = soup.b.a['href']
line = '"' + '","'.join((name, url, addr1, addr2, phone)) + '"'
print line
f.write((line + '\n').encode('utf8'))
except KeyboardInterrupt:
break
except:
print 'Rejected: {}'.format(i)
rej.write('{}\n'.format(i))
f.close()
rej.close()
The error I get is:
File "/Users/Spencer/Downloads/xmlmaker.py", line 18
_, addr1, new_line1 = line1.split(',')[0], new_line2 = line1.split(',')[1] + ', ' + line2, phone = [foo.replace('"', '""') for foo in splitted]
SyntaxError: can't assign to operator
Any ideas? I was looking and saw maybe some mispelling, but I just don't know.
Put those statements on separate lines:
_, addr1, new_line1 = line1.split(',')[0]
new_line2 = line1.split(',')[1] + ', ' + line2
phone = [foo.replace('"', '""') for foo in splitted]
Use ; to separate statements on a single line not ,. But it is less readable so it's better to put them on separate lines :
>>> x = 1; y = 2
>>> x,y
(1, 2)
From PEP-8:
Compound statements (multiple statements on the same line) are
generally discouraged.
You cannot treat assignments as values, i.e. there can not be an expression to the left of = (and only one = per line except for chained assignments like a = b = c = 0). Replace the monster line
_, addr1, new_line1 = line1.split(',')[0], new_line2 = line1.split(',')[1] + ', ' + line2, phone = [foo.replace('"', '""') for foo in splitted]
with something like
phone = [foo.replace('"', '""') for foo in splitted]
new_line2 = line1.split(',')[1] + ', ' + line2
_, addr1, new_line1 = line1.split(',')[0]

Categories

Resources