为什么这段代码会产生错误“AttributeError: 'Match' object has no attribute 'replace'"? [英] Why does this code produce the error "AttributeError: 'Match' object has no attribute 'replace'"?

查看:69
本文介绍了为什么这段代码会产生错误“AttributeError: 'Match' object has no attribute 'replace'"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下基本脚本,我可以使用体育包裹:

With the following basic script, I am able to get all current matches using the sports package:

import sports
all_matches = sports.all_matches()
s = all_matches['soccer']
print(s)

>> [Saham 1-2 Al Shabab, Cuanda Cubango FC 1-2 Academica Lobito, Recreativo Da Caala 0-2 Primeiro De Agosto, Progresso Associacao 0-0 Santa Rita De Cassia, Wapda 1-1 Karachi Electric, Tooro United 2-0 Bright Stars FC, Bul FC 2-2 Nyamityobora, Paidha Black Angels 1-1 Maroons FC, Express FC 0-0 Ndejje University, Pakistan Navy 1-0 National Bank, La Roda 0-0 Atletico Ibanes] [Finished in 10.4s]


我希望拆分列表,以便每行都可以找到一个匹配项,如下所示:


I am looking to split the list so that I get a match per line like so:

import sports
all_matches = sports.all_matches()
s = all_matches['soccer']
soccer = [i.replace(',', '\n') for i in s]
print(soccer)


AttributeError: 'Match' object has no attribute 'replace'

希望的输出:

>>[Saham 1-2 Al Shabab
>>Cuanda Cubango FC 1-2 Academica Lobito
>>Recreativo Da Caala 0-2 Primeiro De Agosto
>>Progresso Associacao 0-0 Santa Rita De Cassia
>>Wapda 1-1 Karachi Electric
>>Tooro United 2-0 Bright Stars FC

推荐答案

正在使用的库中的 Match 类定义相同的 __ repr __ __ str __ 方法,这些方法返回字符串包括主队名称,主队得分,客队得分和客队名称.这就是为什么在打印匹配项列表时看到结果的原因.

The Match class in the library that you are using defines identical __repr__ and __str__ methods which return a string comprising the home team name, the home team score, the away team score and the away team name. That's why you see the results when you print the list of matches.

您的变量 s Match 对象的列表.

有两种方法可以将每个匹配项打印在单独的行上.

There are two ways to print each match on a separate line.

您可以使用for循环打印每个匹配项:

You can use for loop to print each match:

>>> for m in matches:
...     print(m)
... 
Saham 1-2 Al Shabab
Cuanda Cubango FC 1-2 Academica Lobito
Recreativo Da Caala 0-2 Primeiro De Agosto
Progresso Associacao 0-0 Santa Rita De Cassia
Wapda 1-1 Karachi Electric
Tooro United 2-0 Bright Stars FC
Bul FC 2-2 Nyamityobora
Paidha Black Angels 1-1 Maroons FC
Express FC 0-0 Ndejje University
Pakistan Navy 1-0 National Bank
La Roda 0-0 Atletico Ibanes 

或您可以使用 str.join 方法:

>>> print('\n'.join(str(x) for x in matches))
Saham 1-2 Al Shabab
Cuanda Cubango FC 1-2 Academica Lobito
Recreativo Da Caala 0-2 Primeiro De Agosto
Progresso Associacao 0-0 Santa Rita De Cassia
Wapda 1-1 Karachi Electric
Tooro United 2-0 Bright Stars FC
Bul FC 2-2 Nyamityobora
Paidha Black Angels 1-1 Maroons FC
Express FC 0-0 Ndejje University
Pakistan Navy 1-0 National Bank
La Roda 0-0 Atletico Ibanes

这篇关于为什么这段代码会产生错误“AttributeError: 'Match' object has no attribute 'replace'"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆