如何在python中使用generator生成文本?

2024-04-20 05:44:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python生成器生成一个文本

我是一个初学者,最近开始学习python,我在网上搜索了一下,但是没有发现任何有用的东西

def make_text(n):
    b = ["hello"]
    yield n+b
n = ['how are you', 'what is your name']
for x in range(2):
    title = driver.find_element_by_xpath('//*[@id="title"]')
    title.send_keys(make_text(n))

我想得到:

hello how are you 
hello what's your name? 

但我有个错误:

object of type 'generator' has no len() 

提前谢谢


Tags: textname文本youhelloyourmaketitle
2条回答

更适合初学者的代码版本是:

def make_text(n):
    b = ["hello"]
    return n + b

words = ['how are you', 'what is your name']

for word in words:
    text = make_text(word)
    print(text)

这是一个你能做的基本例子。需要迭代yielded对象

def make_text(word):
    greetings = ['how are you', 'what is your name']
    for greet in greetings:
        yield "{} {}".format(word, greet)

def say():
    texts = ['hello',]
    for text in texts:
        x = make_text(text)
        for n in x:
            print(n)
            title = driver.find_element_by_xpath('//*[@id="title"]')
            title.send_keys(n)


say()

输出

hello how are you
hello what is your name

相关问题 更多 >