|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
前一段时间在想做一个简单的chatroom ,主要功能就是实现对话翻译。但是我遇到了一个问题, AttributeError。 我看了网上的解决方法例如删掉pyc文件的东西,和改文件名,但是都没有成功。
代码如下:
#server.py
import socket
import translator
s = socket.socket()
ip = 'localhost'
port = 8000
s.bind((ip,port))
s.listen(1)
print("Wait for client")
c, addr = s.accept()
print ('client added !')
while True:
msg1 = input (">>>")
translator.transword = msg1
output = translator.current_content
c.send(output.encode())
print (c.recv(1024).decode())
#client.py
import socket
import translator
s = socket.socket()
ip = 'localhost'
port = 8000
s.connect((ip,port))
print ('Connected ! ')
while True:
print(s.recv(1024).decode())
msg2 = input (">>>")
translator.transword = msg2
output = translator.current_content
s.send(output.encode())
#translator.py
from urllib import request,parse
import json
class fanyi():
def translate(word):
base_url = "http://fy.iciba.com/ajax.php?a=fy"
data = {
"f": "auto",
"t": "auto",
"w": word
}
data_str = parse.urlencode(data)
header = {"User-Agent":" Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36"}
response = request.Request(url=base_url,headers = header,data = bytes(data_str,encoding="utf-8"))
req = request.urlopen(response).read().decode("utf-8")
obj =json.loads(req)
return obj
if __name__ == "__main__":
word = transword
trans_word = translate(word)
current_state = trans_word["status"]
if current_state == 1:
current_content = trans_word["content"]
else:
current_content = trans_word["content"]
fanyi()
求大佬指点迷经!! 如果有更好完善代码的方法就更好了!!! 感谢!!!!
对你的代码做了点改动,如果要翻译中文需要加判断
#server.py
import socket
import translator
s = socket.socket()
ip = 'localhost'
port = 8000
s.bind((ip,port))
s.listen(1)
print("Wait for client")
c, addr = s.accept()
print ('client added !')
while True:
msg1 = input (">>>")
output = translator.translate(msg1)["content"]["word_mean"][0]
c.send(output.encode("utf-8"))
print (c.recv(1024).decode())
#client.py
import socket
import translator
s = socket.socket()
ip = 'localhost'
port = 8000
s.connect((ip,port))
print ('Connected ! ')
while True:
print(s.recv(1024).decode())
msg2 = input (">>>")
output = translator.translate(msg2)["content"]["word_mean"][0]
s.send(output.encode("utf-8"))
#translator.py
from urllib import request,parse
import json
def translate(word):
base_url = "http://fy.iciba.com/ajax.php?a=fy"
data = {
"f": "auto",
"t": "auto",
"w": word
}
data_str = parse.urlencode(data)
header = {"User-Agent":" Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36"}
response = request.Request(url=base_url,headers = header,data = bytes(data_str,encoding="utf-8"))
req = request.urlopen(response).read().decode("utf-8")
obj =json.loads(req)
return obj
|
|