无法将元组转换为字符串我该怎么办?

时间:2019-10-01 12:53:32

标签: python string tuples

我正试图将元组的out_chars转换为字符串。但是,这似乎很麻烦,因为存在while循环,并且状态将其定义为元组。我该怎么办

我尝试def convertString但未成功

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))

回溯(最近通话最近一次):

  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

3 个答案:

答案 0 :(得分:0)

您的元组包含什么?它包含复杂的对象或简单的字符串数字等吗??? 从上面发布的内容很难理解您的问题。但是如果您想将元组转换为字符串,可以这样做

 new_str = ''.join(yourtuple)

答案 1 :(得分:0)

我不确定您是否正确理解了您的问题,但是如果您想从元组中创建一个字符串,那真的很简单。

def convertTuple(tup): 
    str =  ''.join(tup) 
    return str

tuple = ('g', 'e', 'e', 'k', 's') 
str = convertTuple(tuple) 
print(str) 

答案 2 :(得分:0)

如果不能确保元组的所有元素都是字符串,则必须强制转换它们。

''.join([str(elem) for elem in myTuple])