【问题标题】:How can I single out certain elements in a list and get an output with user input?如何挑选出列表中的某些元素并通过用户输入获得输出?
【发布时间】:2021-03-04 20:21:25
【问题描述】:

所以我正在尝试使用 python 编写代码,其中用户输入某个输入,作为回报,它会给出一个列表,其中仅包含前面带有 (#) 的单词。

def labeled():
message_input = input("Enter a message or type q to end:").split()
result = list(message_input)
lstA =[]
for i in result:
    if '#' in i :
        lstA.append(i[1:])
        continue
print(lstA)
else:
    import sys
    sys.exit()
    break

到目前为止,我能够获取用户输入的消息并给出一个列表作为输出,但我希望用户输入一条消息(例如:“Nice day today #running #marathon”)并让 python 返回[跑步,马拉松]。考虑到这一点,如果单词末尾也有标点符号,我将如何删除它(例如:#marathon。)输出应该是 [marathon]。

如果用户专门输入 q,我也试图让程序退出,但在用户按下 q 之前,系统应继续要求用户输入消息,一旦他们退出,它会返回用户输入的列表。

【问题讨论】:

  • 提示:字符串有一个startswith() 方法。请注意,您还选择了其中某处有 # 的字符串,这与您描述的不同。

标签: python list input user-input


【解决方案1】:

您可以通过以下方式使用翻译来查找特定字符:

def test():
    while(True):
        result = input("Enter a message or type q to end:")
        lstA =[]
        if result =='q':
            break
        else:
            for i in result.split():
                if i.startswith('#'):
                    lstA.append(i.translate({ord('#'): None}))
            print(lstA)

## calling test function 
test()

希望能解决你的问题。

【讨论】:

  • 是的,到目前为止,这似乎已经奏效了,当我输入“今天美好的一天#running #marathon”之类的消息时,当我试图获取列表中标签中的特定单词。如果我输入“今天美好的一天#running #marathon”,它们的输出应该是 [running, marathon]
  • 完美!!!谢谢!!有没有办法在我退出时python可以输出我输入的所有消息并最终制定出来?
  • @Jake,我很高兴,它有帮助!!接受并投票赞成我提出的解决方案。你可以连接你想在最后显示的消息,如果你想要清理文本,那么你可以从函数中创建一个全局列表,并在函数中附加你需要的所有内容。
【解决方案2】:

例如,可以使用正则表达式搜索以# 为前缀的任何字母数字字符串

import re
def labeled(s):
    return re.findall(r'#([\w\d]+)', s)

>>> labeled("Nice day today #running #marathon")
['running', 'marathon']

同样你可以str.split空格上的字符串并保留str.startwith一个'#'字符的所有子字符串

def labeled(s):
    return [i[1:] for i in s.split() if i.startswith('#')]

>>> labeled("Nice day today #running #marathon")
['running', 'marathon']

【讨论】:

    猜你喜欢
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多