gpt4 book ai didi

python - 如何从字符串中提取整数

转载 作者:太空宇宙 更新时间:2023-11-04 05:13:48 24 4
gpt4 key购买 nike

我正在尝试求出这两个数字的和。这些是我的服务器和客户端代码,我想要的结果是

客户收到:总数 46

但是我得到了

客户收到:总数 12

客户收到:总数 34

客户:

    import socket

def parse_file(fName):
list = []
with open(fName) as f:
for line in 1f:
list.append(line.strip())
return list


HOST = 'localhost' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

input_data = parse_file('foo')

for i in input_data:
s.sendall(str(i))
sum = s.recv(1024)
print "CLIENT RECEIVED : Sum ", sum

s.close()

服务器:

import socket

def compute_sum(line):
result = sum(int(i) for i in line)
return result

HOST = 'localhost' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
print "SERVER RECIEVED : ", repr(data)
compute_sum(data)

conn.sendall(data)
conn.close()

23
12

最佳答案

您的 print 语句在您的循环中,并且每次通过时 sum 都被设置为新值,而不是增加适当的数量。试试这个:

sum = 0

for i in input_data:
s.sendall(str(i))
sum += int(s.recv(1024))

print "CLIENT RECEIVED : Sum ", sum

关于python - 如何从字符串中提取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42311004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com