![](/img/trans.png)
[英]must be str, not bytes | 'str' has no attribute 'decode'
[英]'str' object has no attribute 'decode' & "write() argument must be str, not bytes"
我想使用 Amazon Polly 制作一個簡單的 Web 應用程序。
這是我的目錄結構。
.
├── data.txt
├── main.py
└── templates
└── index.html
這是我的 main.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask
from flask import render_template
from flask import request
from flask import send_file
from boto3 import Session
import os
import csv
from io import StringIO
from contextlib import closing
app = Flask(__name__)
@app.route("/", methods=['POST', 'GET'])
def index():
if request.method == "POST":
## Sessionを作成
session = Session(aws_access_key_id='???', aws_secret_access_key='???', region_name='us-east-1')
polly = session.client("polly")
## polly.mp3が存在した場合は削除
if os.path.isfile('/tmp/output.mp3'):
os.remove ('/tmp/output.mp3')
## data.txtをCSVとして読み込む
f = open('data.txt')
reader = csv.reader(f)
## CSVを1行ずつ読み込む
for line in reader:
## CSVの1つめの項目で男女を切り替え
if line[0] == "M":
voice="Matthew"
elif line[0] == "F":
voice="Joanna"
## 音聲データを作成
response = polly.synthesize_speech(
Text = '<speak><amazon:domain name="conversational"><prosody rate="slow">' + line[1].decode("utf-8") + '</prosody></amazon:domain></speak>',
OutputFormat = "mp3",
VoiceId = voice, Engine='neural', TextType='ssml')
## polly.mp3に追加書き込み
if "AudioStream" in response:
with closing(response["AudioStream"]) as stream:
data = stream.read()
fw = open("/tmp/output.mp3", "a+")
fw.write(data)
fw.close()
f.close()
return send_file("/tmp/output.mp3",as_attachment=True)
else:
return render_template("index.html")
if __name__ == "__main__":
app.run()
這是我的 index.html
<html>
<body>
<form action="/" method="POST">
<input type="submit" value="download">
</form>
</body>
</html>
當我在本地(Windows10、Windows Subsystems for Linux、Debian、Python3.7.6)測試此代碼時,收到此錯誤消息。
File "main.py", line 41, in index
Text = '<speak><amazon:domain name="conversational"><prosody rate="slow">' + line[1].decode("utf-8") + '</prosody></amazon:domain></speak>',
AttributeError: 'str' object has no attribute 'decode'
所以,我在互聯網上搜索並找到了這個頁面。 'str' 對象沒有屬性 'decode'。 Python 3 錯誤?
我刪除 .decode('utf-8') 部分:
Text = '<speak><amazon:domain name="conversational"><prosody rate="slow">' + line[1] + '</prosody></amazon:domain></speak>',
然后我收到了一條新的錯誤消息。
File "main.py", line 50, in index
fw.write(data)
TypeError: write() argument must be str, not bytes
我搜索了“write() 參數必須是 str,而不是字節”。 許多網站建議我應該放置 .decode('utf-8') 部分。
你能給我任何信息或建議嗎?
正如@furas 評論的那樣,
open("/tmp/output.mp3", "ba+")
完美地工作。 謝謝@furas!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.