Can't convert tuple to string what can I do? - python

I am trying to turn to out_chars from tuple to string. However, it seems quite troublesome since there is while loop and the state defined its to be tuple. What should I do
I try def convertString but not succesful
out_chars = []
string = ()
for i, char_token in enumerate(computer_response_generator):
out_chars.append(chars[char_token])
print(possibly_escaped_char(out_chars), end='', flush=True)
states = forward_text(net, sess, states, relevance, vocab, chars[char_token])
if i >= max_length:
break
states = forward_text(net, sess, states, relevance, vocab, sanitize_text(vocab, "\n> "))
states = convertTuple(states)
string = convertTuple(out_chars)
print(Text_to_sp(string, states))
Traceback (most recent call last):
File "/Users/quanducduy/anaconda3/chatbot-rnn-master/chatbot.py", line 358, in <module>
main()
File "/Users/quanducduy/anaconda3/chatbot-rnn-master/chatbot.py", line 44, in main
sample_main(args)
File "/Users/quanducduy/anaconda3/chatbot-rnn-master/chatbot.py", line 92, in sample_main
args.relevance, args.temperature, args.topn, convertTuple)
File "/Users/quanducduy/anaconda3/chatbot-rnn-master/chatbot.py", line 169, in chatbot
print(Text_to_sp(string, states))
File "/Users/quanducduy/anaconda3/chatbot-rnn-master/Text_to_speech.py", line 28, in Text_to_sp
myobj.save("welcome.mp3")
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gtts/tts.py", line 249, in save
self.write_to_fp(f)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gtts/tts.py", line 182, in write_to_fp
text_parts = self._tokenize(self.text)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gtts/tts.py", line 144, in _tokenize
text = text.strip()
AttributeError: 'tuple' object has no attribute 'strip'
Process finished with exit code 1

what does your tuple contains?? does it contain complex objects or simple strings numbers etc???
your problem is hard to understand from what you have posted above. but if you want o convert tuple to string you can do like this
new_str = ''.join(yourtuple)

I'm not sure that understand your question right, but if you want to make a string from tuple, its really simple.
def convertTuple(tup):
str = ''.join(tup)
return str
tuple = ('g', 'e', 'e', 'k', 's')
str = convertTuple(tuple)
print(str)

If you cannot ensure all the elements of the tuple are strings, you have to cast them.
''.join([str(elem) for elem in myTuple])

Related

Pathlib and stem - Attributerror

as part of a code I have function as follow:
def match_output(orig_path: Path,lines: Iterable[str],stem: str, delim: str,delim_pred: Callable[[int], bool],) -> Iterable:
n = 0
path = orig_path.with_stem(f'{orig_path.stem}_{stem}')
with path.open('w') as f:
for line in lines:
n_delim = line.count(delim)
matched = delim_pred(n_delim)
if matched:
f.write(line)
n += int(matched)
yield
logger.info(f'Number of {stem} lines: {n}')
However, I am getting attribute error, couldn't solve it, would appreciate any suggestion?
Traceback (most recent call last):
File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 95, in <module>
main()
File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 88, in main
process(
File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 82, in process
for n_lines, _ in enumerate(zip(*iters)):
File "C:/Users/HAXY8W/Desktop/pieter_code_rewriting/main.py", line 27, in match_output
path = orig_path.with_stem(f'{orig_path.stem}_{stem}')
AttributeError: 'WindowsPath' object has no attribute 'with_stem'
I am very new to Pathlib and stem, someone smarter than me recommended that I look into it so apologize if the question sounds newbie
path.with_stem() was introduced in Python 3.9. In previous versions (that support path objects) you can do it manually:
path = orig_path.with_name(f'{orig_path.stem}_{stem}{orig_path.suffix}')

I don't understan why checksum error occurs

I found on Internet pynmea2 library, that used the parse(data, check=False) function, which takes a string containing a NMEA 0183 sentence and returns a NMEASentence object.
I try to write some easy (very easy) code to understand functioning:
import pynmea2
def main():
f = open("file.nmea", "r")
for line in f.readlines():
msg = pynmea2.parse(line)
print(str(msg))
So, I read sentences from a file and passed them to parse function, but an error raise:
Traceback (most recent call last):
File "/home/maestrutti15/PycharmProjects/prova/main.py", line 13, in <module>
main()
File "/home/maestrutti15/PycharmProjects/prova/main.py", line 9, in main
msg = pynmea2.parse(str(line))
File "/home/maestrutti15/PycharmProjects/prova/venv/lib/python3.8/site-packages/pynmea2/nmea.py", line 115, in parse
raise ChecksumError(
pynmea2.nmea.ChecksumError: ('checksum does not match: 17 != 3B', ['121626.10', 'A', '4608.25657', 'N', '01313.38859', 'E', '0.071', '270421', 'A', 'V'])
Can anyone tell me why this errors appears? I don't understand... if I write
msg = pynmea2.parse("$GNRMC,121626.15, ..)
in this way, it prints the result.
Thank you!

Python - U.S. ZipCode Matching

I'm working with Regex and I'm brand new to using python. I can't get the program to read from file and go through the match case properly. I'm getting a traceback error that looks like this:
Traceback (most recent call last):
File "C:\Users\Systematic\workspace\Project8\src\zipcode.py", line 18, in <module>
m = re.match(info, pattern)
File "C:\Python34\lib\re.py", line 160, in match
return _compile(pattern, flags).match(string)
File "C:\Python34\lib\re.py", line 282, in _compile
p, loc = _cache[type(pattern), pattern, flags]
TypeError: unhashable type: 'list'
zipin.txt:
3285
32816
32816-2362
32765-a234
32765-23
99999-9999
zipcode.py:
from pip._vendor.distlib.compat import raw_input
import re
userinput = raw_input('Please enter the name of the file containing the input zipcodes: ')
myfile = open(userinput)
info = myfile.readlines()
pattern = '^[0-9]{5}(?:-[0-9]{4})?$'
m = re.match(info, pattern)
if m is not None:
print("Match found - valid U.S. zipcode: " , info, "\n")
else: print("Error - no match - invalid U.S. zipcode: ", info, "\n")
myfile.close()
The problem is that readlines() returns a list, and re operates on stuff that is string like. Here is one way it could work:
import re
zip_re = re.compile('^[0-9]{5}(?:-[0-9]{4})?$')
for l in open('zipin.txt', 'r'):
m = zip_re.match(l.strip())
if m:
print l
break
if m is None:
print("Error - no match")
The code now operates in a loop over the file lines, and attempts to match the re on a stripped version of each line.
Edit:
It's actually possible to write this in a much shorter, albeit less clear way:
next((l for l in open('zipin.txt', 'r') if zip_re.match(l.strip())), None)

Python Search & Replace With Regex

I am trying to replace every occurrence of a Regex expression in a file using Python with this code:
import re
def cleanString(string):
string = string.replace(" ", "_")
string = string.replace('_"', "")
string = string.replace('"', '')
return string
test = open('test.t.txt', "w+")
test = re.sub(r':([\"])(?:(?=(\\?))\2.)*?\1', cleanString(r':([\"])(?:(?=(\\?))\2.)*?\1'), test)
However, when I run the script I am getting the following error:
Traceback (most recent call last):
File "C:/Python27/test.py", line 10, in <module>
test = re.sub(r':([\"])(?:(?=(\\?))\2.)*?\1', cleanString(r':([\"])(?:(?=(\\?))\2.)*?\1'), test)
File "C:\Python27\lib\re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
I think it is reading the file incorrectly but I'm not sure what the actual issue is here
Your cleanString function is not returning anything. Ergo the "NoneType" error.
You probably want to do something like:
def cleanString(string):
string = string.replace(" ", "_")
string = string.replace('_"', "")
string = string.replace('"', '')
return string

how to serialize an array/list/mat filled with complex number

I want to serialize an ndarray/list filled with complex number, the example code is here:
a = [None]
a[0] = 0.006863076166054825+0j
a
[(0.006863076166054825+0j)]
>>> b = json.dumps(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Python27\lib\json\__init__.py", line 243, in dumps
return _default_encoder.encode(obj)
File "D:\Python27\lib\json\encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "D:\Python27\lib\json\encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "D:\Python27\lib\json\encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: (0.006863076166054825+0j) is not JSON serializable
so how to deal with the problem?
The json.dumps(a) will fail, because the function can not handle the complex number when it tries to interpret it. The only possibility to pass the value is as string:
a = [1]
a[0] = "0.006863076166054825+0j"
b = json.dumps(a)
print b
which outputs
["0.006863076166054825+0j"]
ok let me make it clear
I found another way to do it.
use the module pickle
eg:
fp = open("1.txt","w")
a = [1,2,3]
pickle.dump(a,fp,0)
fp.close()
to load is the same:
fp = open("1.txt")
a = pickle.load(fp)
print a
fp.close()
it can serialize any object as long as it can find the class
I needed this problem's solution too. I have written this code and it works for the task that I need, but when I ran it through checks it does not complete all the tasks. Still, one can use it.
# turn complex to str
def replace_complex( inp):
"""Replace complex numbers with strings of
complex number + __ in the beginning.
Parameters:
------------
inp: input dictionary.
"""
try:
if isinstance(inp, complex):
return "__" + str(inp)
elif isinstance(inp, list):
for each in range(len(inp)):
inp[ each] = replace_complex( inp[ each])
return inp
elif isinstance(inp, dict):
for key,val in inp.items():
inp[key] = replace_complex( val)
return inp
else:
return inp # nothing found - better than no checks
except Exception as e:
print(e)
return ""

Categories

Resources