Меню

Ошибка list object has no attribute replace

I am trying to remove the character ‘ from my string by doing the following

kickoff = tree.xpath('//*[@id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/b[1]/text()')
kickoff = kickoff.replace("'", "")

This gives me the error AttributeError: ‘list’ object has no attribute ‘replace’

Coming from a php background I am unsure what the correct way to do this is?

falsetru's user avatar

falsetru

349k62 gold badges701 silver badges621 bronze badges

asked Apr 15, 2016 at 9:03

emma perkins's user avatar

2

xpath method returns a list, you need to iterate items.

kickoff = [item.replace("'", "") for item in kickoff]

answered Apr 15, 2016 at 9:05

falsetru's user avatar

falsetrufalsetru

349k62 gold badges701 silver badges621 bronze badges

2

kickoff = tree.xpath('//*[@id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/b[1]/text()')

This code is returning list not a string.Replace function will not work on list.

[i.replace("'", "") for i in kickoff ]

answered Apr 15, 2016 at 9:06

Himanshu dua's user avatar

Himanshu duaHimanshu dua

2,4461 gold badge17 silver badges27 bronze badges

This worked for me:

kickoff = str(tree.xpath('//*[@id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/b[1]/text()'))
kickoff = kickoff.replace("'", "")

This error is caused because the xpath returns in a list. Lists don’t have the replace attribute. So by putting str before it, you convert it to a string which the code can handle. I hope this helped!

answered Mar 28, 2019 at 3:29

Char Gamer's user avatar

In Python, the list data structure stores elements in sequential order. We can use the String replace() method to replace a specified string with another specified string. However, we cannot apply the replace() method to a list. If you try to use the replace() method on a list, you will raise the error “AttributeError: ‘list’ object has no attribute ‘replace’”.

This tutorial will go into detail on the error definition. We will go through an example that causes the error and how to solve it.


Table of contents

  • AttributeError: ‘list’ object has no attribute ‘replace’
    • Python replace() Syntax
  • Example #1: Using replace() on a List of Strings
    • Solution
  • Example #2: Using split() then replace()
    • Solution
  • Summary

AttributeError: ‘list’ object has no attribute ‘replace’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘list’ object has no attribute ‘replace’” tells us that the list object we are handling does not have the replace attribute. We will raise this error if we try to call the replace() method on a list object. replace() is a string method that replaces a specified string with another specified string.

Python replace() Syntax

The syntax for the String method replace() is as follows:

string.replace(oldvalue, newvalue, count)

Parameters:

  • oldvalue: Required. The string value to search for within string
  • newvalue: Required. The string value to replace the old value
  • count: Optional. A number specifying how many times to replace the old value with the new value. The default is all occurrences

Let’s look at an example of calling the replace() method to remove leading white space from a string:

str_ = "the cat is on the table"

str_ = str.replace("cat", "dog")

print(str_)
the dog is on the table

Now we will see what happens if we try to use the replace() method on a list:

a_list = ["the cat is on the table"]

a_list = a_list.replace("cat", "dog")

print(a_list)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      1 a_list = ["the cat is on the table"]
      2 
----≻ 3 a_list = a_list.replace("cat", "dog")
      4 
      5 print(a_list)

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

The Python interpreter throws the Attribute error because the list object does not have replace() as an attribute.

Example #1: Using replace() on a List of Strings

Let’s look at an example list of strings containing descriptions of different cars. We want to use the replace() method to replace the phrase “car” with “bike”. Let’s look at the code:

lst = ["car one is red", "car two is blue", "car three is green"]

lst = lst.replace('car', 'bike')

print(lst)

Let’s run the code to get the result:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
----≻ 1 lst = lst.replace('car', 'bike')

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

We can only call the replace() method on string objects. If we try to call replace() on a list, we will raise the AttributeError.

Solution

We can use list comprehension to iterate over each string and call the replace() method. Let’s look at the revised code:

lst = ["car one is red", "car two is blue", "car three is green"]

lst_repl = [i.replace('car', 'bike') for i in lst]

print(lst_repl)

List comprehension provides a concise, Pythonic way of accessing elements in a list and generating a new list based on a specified condition. In the above code, we create a new list of strings and replace every occurrence of “car” in each string with “bike”. Let’s run the code to get the result:

['bike one is red', 'bike two is blue', 'bike three is green']

Example #2: Using split() then replace()

A common source of the error is the use of the split() method on a string prior to using replace(). The split() method returns a list of strings, not a string. Therefore if you want to perform any string operations you will have to iterate over the items in the list. Let’s look at an example:

particles_str = "electron,proton,muon,cheese"

We have a string that stores four names separated by commas. Three of the names are correct particle names and the last one “cheese” is not. We want to split the string using the comma separator and then replace the name “cheese” with “neutron”. Let’s look at the implementation that will raise an AttributeError:

particles = str_.split(",")

particles = particles.replace("cheese", "neutron")

Let’s run the code to see the result:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
----≻ 1 particles = particles.replace("cheese", "neutron")

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

The error occurs because particles is a list object, not a string object:

print(particles)
['electron', 'proton', 'muon', 'cheese']

Solution

We need to iterate over the items in the particles list and call the replace() method on each string to solve this error. Let’s look at the revised code:

particles = [i.replace("cheese","neutron") for i in particles]

print(particles)

In the above code, we create a new list of strings and replace every occurrence of “cheese” in each string with “neutron”. Let’s run the code to get the result:

['electron', 'proton', 'muon', 'neutron']

Summary

Congratulations on reading to the end of this tutorial! The error “AttributeError: ‘list’ object has no attribute ‘replace’” occurs when you try to use the replace() function to replace a string with another string on a list of strings.

The replace() function is suitable for string type objects. If you want to use the replace() method, ensure that you iterate over the items in the list of strings and call the replace method on each item. You can use list comprehension to access the items in the list.

Generally, check the type of object you are using before you call the replace() method.

For further reading on AttributeErrors involving the list object, go to the article:

  • How to Solve Python AttributeError: ‘list’ object has no attribute ‘split’.
  • How to Solve Python AttributeError: ‘list’ object has no attribute ‘lower’.
  • How to Solve Python AttributeError: ‘list’ object has no attribute ‘get’.

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

1

25.05.2018, 00:45. Показов 21220. Ответов 12

Метки нет (Все метки)


raceback (most recent call last):
File «/home/vladislav/Документы/python/parse.py», line 11, in <module>
content.replace(‘ — — ‘, ‘ ‘)
AttributeError: ‘list’ object has no attribute ‘replace’
Я несовсем понимаю почему тут такая ошибка , что значит ,что content — это разве список.
это ошибка связана с типом данных или с неправильным присвоением переменной?

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import string
import sys
from var_dump import var_dump
bad_ip={}
file=[]
d=0
mystring=[]
file_content={}
with open('access_log','r') as f:
 content=f.readlines()
 content.replace(' - - ', ' ')
 
 content.split(' ')
 for d in file:
    if d.count(d[1])<=100:
     
     bad_ip['ip']=(d[1])
     bad_ip['count']=d.count(d[1])

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



437 / 429 / 159

Регистрация: 21.05.2016

Сообщений: 1,338

25.05.2018, 01:19

2

Напишите print(content) да посмотрите что там. Там список строк, конечно



0



saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

26.05.2018, 16:29

 [ТС]

3

oldnewyear, я имел ввиду как переменную content дать на вход функции replace.

Python
1
2
3
 content=f.readlines()
 print(content)
 content.replace(content,' - - ', ' ')



0



Эксперт Python

5403 / 3827 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

26.05.2018, 16:39

4

Замените f.readlines() на f.read(), либо обходите список строк в цикле.



0



1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

26.05.2018, 18:29

 [ТС]

5

Garry Galler, вот так и делаю уже



0



Semen-Semenich

3964 / 2946 / 1067

Регистрация: 21.03.2016

Сообщений: 7,452

26.05.2018, 20:53

6

saladdd,
исходя из вашего кода

Python
1
content=f.readlines()

создает список а не строку о чем вам и говорится в ошибки что список не имеет атрибута replace.

справка по методу replace

str.replace(old, new[, maxcount]) -> str
old : Искомая подстрока, которую следует заменить.
new : Подстрока, на которую следует заменить искомую.
maxcount=None : Максимальное требуемое количество замен. Если не указано, будут заменены все вхождения искомой строки
вам не кажется что что то не так ?

Python
1
content.replace(content,' - - ', ' ')



0



saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

26.05.2018, 21:46

 [ТС]

7

Semen-Semenich, мне говорят что вот так вот тоже можно

Python
1
2
3
4
5
6
7
8
9
10
  
content=f.readlines()
 
 
 
         content=content.replace(content,' - - ',' ')
 
         content=content.split(' ')
 
         print(content)



0



Semen-Semenich

3964 / 2946 / 1067

Регистрация: 21.03.2016

Сообщений: 7,452

26.05.2018, 21:56

8

saladdd, вы так и не поняли свою ошибку.

Python
1
2
3
with open('access_log','r') as f:
 content=f.read().replace(' - - ', ' ')
 content=content.split(' ')

или как сказано выше для readlines()

Python
1
2
3
4
with open('access_log','r') as f:
 content=f.readlines()
 for index, str_ in enumerate(content)
   content[index] = str_.replace(' - - ', ' ')



0



saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

27.05.2018, 16:20

 [ТС]

9

Semen-Semenich, я свою ошибку понял , просто не совсем понмял как происходит присвоение.

Добавлено через 35 минут
Semen-Semenich, я свою ошибку понял , просто не совсем понял как происходит присвоение.
Я иею ввиду вот такой вариант

Python
1
  content=content.replace()

и вот такой

Python
1
  content.replace(content,' - - ',' ')

они оба рабочие от чего это завесит, от версии python.



0



Garry Galler

Эксперт Python

5403 / 3827 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

27.05.2018, 17:15

10

Цитата
Сообщение от saladdd
Посмотреть сообщение

они оба рабочие

Этот вариант

Python
1
content.replace(content,' - - ',' ')

не рабочий.
Покажите скрин, где у вас это работает.

Python
1
2
3
4
5
6
7
8
9
10
>>> '1234'.replace("1234","1","0")
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    '1234'.replace("1234","1","0")
TypeError: 'str' object cannot be interpreted as an integer
>>> str.replace("1234","1","0")   #  а вот так можно сделать, потому что replace метод строки (типакласса str)
'0234'
>>> '1234'.replace("1","0")  # но удобнее все-таки делать так
'0234'
>>>



0



saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

27.05.2018, 18:18

 [ТС]

11

Garry Galler, спасибо я с этим вариантом разобрался , тот вариант про который я говорил выше я нашёл на просторах сети скорее всего он и нерабочий, я хотел поинтересоваться.Почему иногда контент передают через аргумент в выражении?

Python
1
content= content.replace(' - - ',' ')



0



Garry Galler

Эксперт Python

5403 / 3827 / 1214

Регистрация: 28.10.2013

Сообщений: 9,554

Записей в блоге: 1

27.05.2018, 18:32

12

Цитата
Сообщение от saladdd
Посмотреть сообщение

Почему иногда контент передают через аргумент в выражении

Потому что это позволяет синтаксис python’а.

Python
1
2
3
4
5
>>> "+".join(['1','2','3','4'])
'1+2+3+4'
>>> str.join('+',['1','2','3','4'])
'1+2+3+4'
>>>

В общем случае такие варианты (через обращение к классу) не особенно нужны.
Однако иногда бывает удобно использовать именно такой синтаксис. Конкретных примеров у меня нет.



0



saladdd

1 / 1 / 1

Регистрация: 23.04.2014

Сообщений: 637

27.05.2018, 18:51

 [ТС]

13

Garry Galler, скажите ,а если способ в моём случае записать разбитую строку content.split(‘ ‘) только чтобы конечный результат
был словарь.
Ну я имею ввиду без цикла и без интераций.

Python
1
2
3
4
5
6
 with open('access_log','r') as f:
 content=f.read()
 content=content.replace(' - - ',' ')
 content=content.split(' ')
 
 print(content)



0



Уведомления

  • Начало
  • » Python для новичков
  • » Ошибка в коде

#1 Ноя. 19, 2015 23:59:15

Ошибка в коде

Есть код:

path = glob.glob("C:...*.txt")
with open("sample_text_collection_metadata.txt", "w", encoding = "utf-8") as metadata_out:
    for txt in test:
        f = open(txt, "r", encoding = "utf-8").read()
        autor_name = f.split("Autor:")[1].replace("r", "").split("n")[0]
        text_file = file.split("Title:")[1].replace("r", "").split("n")[0]
        file_name = file.split("/")[-1]
        metadata_out.write(file_name + "t" + autor_name + "t" + text_file + "n")
        f.close()
        with open("sample_text_collection/" + file_name, "w", "utf-8") as file_out:
            file_out.write(txt)

Загвоздка в том, что когда выполнение кода доходит до autor_name = f.split(“Autor:”).replace(“r”, “”).split(“n”) появляется ошибка AttributeError: ‘list’ object has no attribute ‘replace’
Вопрос: откуда берется ‘list’? если при проверке type(f) мы получаем <class ‘str’>.

Офлайн

  • Пожаловаться

#2 Ноя. 20, 2015 02:36:45

Ошибка в коде

Pytonist
Вопрос: откуда берется ‘list’?

>>> 'a|b|c'.split('|')
['a', 'b', 'c']
>>>

Офлайн

  • Пожаловаться

#3 Ноя. 20, 2015 15:15:12

Ошибка в коде

Уже разобрался. Причина была банальна, было неверно задано условие … Наверное надо перекурить денек второй …

Офлайн

  • Пожаловаться

#4 Ноя. 21, 2015 18:17:27

Ошибка в коде

как сложить все числа, данные в документе?

вот что уже есть:

g=open(‘dfg.txt’, ‘rt’)
s=0
while True:
f = g.readline()
if f == »:
break
n = int(f.strip())

Вот документ:

12
23
45
1
2

зарание спасибо!

Офлайн

  • Пожаловаться

#5 Ноя. 21, 2015 18:28:18

Ошибка в коде

Собрать строки в документе в список, попутно преобразовав в числа и просуммировать через sum

In [1]: sum([1,2,3,4,5])
Out[1]: 15

_________________________
Python golden rule: Do not PEP 8 unto others; only PEP 8 thy self.
Don’t let PEP 8 make you insanely intolerant of other people’s code.

Офлайн

  • Пожаловаться

Во-первых,

for i in range(len(dicts)):
 for x in dicts[i].items():
     dicts[i].items.replace('-','_')

Вы получаете исключение, потому что вы пытаетесь достичь метода «replace» в функции «items», а не вызов функции. так должно быть:

dicts[i].items().replace('-','_')

Во-вторых, для меня это неправильный подход.
Поскольку вы используете python, почему бы не сделать это питоническим способом и просто не вернуть новый список новых dicts с новыми значениями?

Представленная ниже функция берет список dicts списков кортежей (это предоставленная вами структура) и заменяет каждое «to_change» на «change_to». Я вызываю это, используя ваши требования, чтобы изменить каждый знак «-» на «_».

d=[
{
'title': [('Agente 007, Moonraker: Operazione spazio', 'it')], 
'sub-title': [('Missione nel cosmo per...', 'it')], 
},{
'title': [('Agente 007, Vivi e lascia morire', 'it')], 
'sub-title': [('Il primo James Bond con...', 'it')]
}
  ]  

def sub_string(dict_list, to_change, change_to):
    new_list = []
    for d_orig in dict_list:
        d_new = {}
        for key in d_orig.keys():
            new_key = key.replace(to_change, change_to)
            new_value = [[s.replace(to_change, change_to) for s in tup] for tup in d_orig[key]]
            d_new[new_key] = new_value

        new_list.append(d_new)
    return new_list

sub_string(d, '-', '_')

Вы это имели в виду?

ERROR:docstamp.cli.cli:Error filling document for 17th item
Traceback (most recent call last):
File «/opt/anaconda3/envs/acpyss/lib/python3.5/site-packages/docstamp/cli/cli.py», line 152, in create
template_doc.fill(item)
File «/opt/anaconda3/envs/acpyss/lib/python3.5/site-packages/docstamp/template.py», line 220, in fill
doc_contents[key] = replace_chars_for_svg_code(content)
File «/opt/anaconda3/envs/acpyss/lib/python3.5/site-packages/docstamp/svg_utils.py», line 26, in replace_chars_for_svg_code
result = result.replace(c, entity)
AttributeError: ‘list’ object has no attribute ‘replace’
ERROR:docstamp.cli.cli:Error filling document for 21th item
Traceback (most recent call last):
File «/opt/anaconda3/envs/acpyss/lib/python3.5/site-packages/docstamp/cli/cli.py», line 152, in create
template_doc.fill(item)
File «/opt/anaconda3/envs/acpyss/lib/python3.5/site-packages/docstamp/template.py», line 220, in fill
doc_contents[key] = replace_chars_for_svg_code(content)
File «/opt/anaconda3/envs/acpyss/lib/python3.5/site-packages/docstamp/svg_utils.py», line 26, in replace_chars_for_svg_code
result = result.replace(c, entity)
AttributeError: ‘list’ object has no attribute ‘replace’

Thread Rating:

  • 0 Vote(s) — 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5

AttributeError: ‘Response’ object has no attribute ‘replace’

Posts: 404

Threads: 94

Joined: Dec 2017

Reputation:
1

#! python3
# using the inauguration speech of William Henry Harrison analyzed in the previous example, we can write the following code that generates arbitrarily # long Markov chains (with the chain length set to 100) based on the #structure of its text

import requests
from random import randint


def wordListSum(wordList):
    sum = 0
    for word, value in wordList.items():
        sum += value
    return sum


def retrieveRandomWord(wordList):
    randIndex = randint(1, wordListSum(wordList))
    for word, value in wordList.items():
        randIndex -= value
        if randIndex <= 0:
            return word


def buildWordDict(text):
    # Remove newlines and quotes
    text = text.replace("n", " ")
    text = text.replace('"', "")
    # Make sure punctuation marks are treated as their own "words"
    # so that they will be included in the Markov chain
    punctuation = [",", ".", ";", ":"]
    for symbol in punctuation:
        text = text.replace(symbol, " " + symbol + " ")
    words = text.split(" ")
    # Filter out empty words
    words = [word for word in words if word != ""]
    wordDict = {}
    for i in range(1, len(words)):
        if words[i - 1] not in wordDict:
            # Create a new dictionary for this word
            wordDict[words[i - 1]] = {}
        if words[i] not in wordDict[words[i - 1]]:
            wordDict[words[i - 1]][words[i]] = 0
        wordDict[words[i - 1]][words[i]] += 1
    return wordDict


text = requests.get("http://pythonscraping.com/files/inaugurationSpeech.txt")
if text.status_code == 200:
    content = text.text
wordDict = buildWordDict(text)


# Generate a Markov chain of length 100
length = 100
chain = ""
currentWord = "I"
for i in range(0, length):
    chain += currentWord + " "
    currentWord = retrieveRandomWord(wordDict[currentWord])

print(chain)

Error:

Traceback (most recent call last): File "C:Python36kodovimarkov.py", line 49, in <module> wordDict = buildWordDict(text) File "C:Python36kodovimarkov.py", line 25, in buildWordDict text = text.replace("n", " ") AttributeError: 'Response' object has no attribute 'replace' >>>

There is a replace method in the documentation, does this message means that there is not attribute new line?
And what is wrong with the line 49?

Posts: 4,229

Threads: 97

Joined: Sep 2016

Reputation:
273

requests.get returns a Request object, which has no replace method. If you want to use the string replace method, you need to get the text attribute of the Request object, and use replace on that.

Truman

Minister of Silly Walks


Posts: 404

Threads: 94

Joined: Dec 2017

Reputation:
1

Thank you, this is how it should be done:

text = requests.get("http://pythonscraping.com/files/inaugurationSpeech.txt")
if text.status_code == 200:
    content = text.text
wordDict = buildWordDict(content)

Truman

Minister of Silly Walks


Posts: 404

Threads: 94

Joined: Dec 2017

Reputation:
1

It may be off topic but would anyone be so kind to give me further explanations on lines 36-42. It’s about creating two-dimensional dictionary but it looks confusing to me.

Posts: 4,229

Threads: 97

Joined: Sep 2016

Reputation:
273

Line 36 is looping through the indexes of the words list. Not very pythonic. You should loop over items, not the indexes. This loop is meant to be over pairs of consecutive words, but there are ways to do that without resorting to indexes.

Lines 37 and 39 create a sub-dictionary for the previous word (note the for loop starts with 1, the index of the second word) if it doesn’t already have one. You could use collections.defaultdict(dict) instead.

Lines 40 and 41 creates a zero count for the current word if it’s not in the sub-dictionary for the previous word. Again, you could do this with collections.defaultdict(int) instead, but it’s not clear to me how to initialize the nested defaultdicts.

Finally, line 42 adds one to the count of the current word in the previous word’s sub dictionary. So it’s creating a dictionary with counts of pairs of words. Frex, wordDict[‘spam’][‘eggs’] would be the number of times the word ‘eggs’ occurred after the word ‘spam’.

Truman

Minister of Silly Walks


Posts: 404

Threads: 94

Joined: Dec 2017

Reputation:
1

I am a shame of my ignorance but will dare to ask. What does this piece of code means:

 for word, value in wordList.items():
        randIndex -= value
        if randIndex <= 0:
            return word

why randIndex-value?

Posts: 4,229

Threads: 97

Joined: Sep 2016

Reputation:
273

It’s a way to do a weighted random selection. You have a dictionary of words and their weight (the value). You make a random number from 1 to the total of the weights (that’s what is in randIndex). Then you go through the words and subtract each word’s value from randIndex (randIncex -= value is equivalent to randIndex = randIndex - value). When randIndex gets to zero or less, that is your weighted random choice. It makes it so that a word with value v is selected with a probability v / t, where t is the sum of all the values.

In 3.6+, the random module has choices, which can handle this for you more efficiently. However, prior to that you have to use code like the above.

Truman

Minister of Silly Walks


Posts: 404

Threads: 94

Joined: Dec 2017

Reputation:
1

Does that mean that some words will never be returned? Or they will because dictionaries are unordered? In that case, why do we need to do this calculation if we can randomly choose any word?

Posts: 4,229

Threads: 97

Joined: Sep 2016

Reputation:
273

Mar-19-2019, 11:37 PM
(This post was last modified: Mar-19-2019, 11:37 PM by ichabod801.)

(Mar-19-2019, 11:31 PM)Truman Wrote: Does that mean that some words will never be returned? Or they will because dictionaries are unordered? In that case, why do we need to do this calculation if we can randomly choose any word?

The only time a word would never be returned is if it’s weight was 0. Then it would have a probability 0 / t of being returned. It means that some words are more likely to be returned than others, and some words are less like to be returned than others. The standard random.choice() selects every item in the provided sequence with equal likelihood.

Truman

Minister of Silly Walks


Posts: 404

Threads: 94

Joined: Dec 2017

Reputation:
1

(Mar-19-2019, 11:37 PM)ichabod801 Wrote:

(Mar-19-2019, 11:31 PM)Truman Wrote: Does that mean that some words will never be returned? Or they will because dictionaries are unordered? In that case, why do we need to do this calculation if we can randomly choose any word?

The only time a word would never be returned is if it’s weight was 0. Then it would have a probability 0 / t of being returned. It means that some words are more likely to be returned than others, and some words are less like to be returned than others. The standard random.choice() selects every item in the provided sequence with equal likelihood.

That’s exactly why I don’t understand why the author of this code used weighted random selection. Wouldn’t it be more ‘fair’ that each word has an equal chance of being selected?

Possibly Related Threads…
Thread Author Replies Views Last Post
  AttributeError: ‘ellipsis’ object has no attribute ‘register_blueprint’ Mechanicalpixelz 2 1,408 Dec-29-2021, 01:30 AM
Last Post: Mechanicalpixelz
  AttributeError: ‘NoneType’ object in a parser — stops it apollo 4 2,945 May-28-2021, 02:13 PM
Last Post: Daring_T
  AttributeError: ResultSet object has no attribute ‘get_text’ KatMac 1 3,121 May-07-2021, 05:32 PM
Last Post: snippsat
  Python 3.9 : BeautifulSoup: ‘NoneType’ object has no attribute ‘text’ fudgemasterultra 1 6,897 Mar-03-2021, 09:40 AM
Last Post: Larz60+
  ‘NavigableString’ object has no attribute ‘h2’ RandomCoder 5 3,746 May-20-2020, 09:01 AM
Last Post: Larz60+
  AttributeError: ‘str’ object has no attribute ‘xpath’ nazmulfinance 4 8,489 Nov-11-2019, 05:15 PM
Last Post: nazmulfinance
  AttributeError: ‘str’ object has no attribute ‘xpath’ nazmulfinance 0 2,316 Nov-10-2019, 09:13 PM
Last Post: nazmulfinance
  form.populate_obj problem «object has no attribute translate» pascale 0 2,978 Jun-12-2019, 07:30 PM
Last Post: pascale
  Error object has no attribute text hcyeap 3 12,679 May-21-2019, 07:12 AM
Last Post: buran
  AttributeError: ‘dict’ object has no attribute ‘is_active’ (PyMongo And Flask) usman 0 4,119 Nov-20-2018, 09:50 PM
Last Post: usman

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка link2ea launch game
  • Ошибка link2ea battlefield 4