两个列表项合并的标准

3
我正在编写一个支持语音的个人助手,它可以发送电子邮件、查看天气和打开网站。
我正在使用Google Voice API将我的语音转换为文字。当我说“Open funny dot reddit dot com”时,Google会将其识别为'Funny.Reddit.com'。因此,我需要一种方法,使点号之前的任何内容与.com的字符串合并。
text = ['open', 'funny.', 'Reddit.com']
if 'open' in text:
        print(text)
        text = text.split()
        sub = 'com'
        www = 'www'
        wcheck = ("\n".join(s for s in text if www in s))
        website = ("\n".join(s for s in text if sub in s))
        if 'www' in wcheck:
            web.open(website)
        if 'www' not in wcheck:
            web.open('www.' + website)

prefix = "\n".join(s for s in text if '%s.' in s)前缀 = "\n".join(s for s in text if '%s.' in s) - Will
我不是完全确定你想要做什么。prefix = "\n".join(s for s in text if '%s.' in s) 会通过换行符将单词或字符连接起来。你的意图不是创建有效的URL吗? - jDo
我的错,我只是不确定该怎么做。 - Will
我确实有个例子(差不多)。谷歌返回“open funny. Reddit.com”,然后我把它分成了两部分。 - Will
我有的代码只要我说“打开reddit.com”就能运行。 - Will
显示剩余2条评论
1个回答

1

将符合特定条件的列表元素组合起来的一般方法是首先创建一个较小的列表,其中仅包含符合条件的项目。在您的情况下,这个列表将是['funny.', 'Reddit.com']。您可以使用列表推导式创建它:

[e for e in text if e.endswith((".",".com",".net",".org",".edu",".gov"))]

完整的答案是:尝试将URL中的每个元素连接起来,以形成完整的URL。
URL = "".join([e for e in text if e.endswith((".",".com",".net",".org",".edu",".gov"))])

这涉及到大多数网站,我想。例如:

>>> text=["open","funny.","reddit.com"]
>>> print "".join([e for e in text if e.endswith((".",".com",".net",".org",".edu",".gov"))])
funny.reddit.com

请注意,这只适用于简单情况,而不适用于像 ["google.com","open","funny。","reddit.com"] 这样的情况,它会输出“google.com.funny.reddit.com”。我假设您的所有输入都相对简单。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接