繁体   English   中英

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

[英]How can I generate a text using generator in 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() 

提前致谢

这是您可以执行的操作的基本示例。 您需要迭代yield ed 对象,

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM