【问题标题】:How to count how many words are in a text string inputted by the user in python如何计算用户在python中输入的文本字符串中有多少个单词
【发布时间】:2013-04-07 13:23:49
【问题描述】:

我想知道是否有人可以提供帮助;我对python很陌生。

我目前正在创建一个工具,它可以分析用户输入的文本并显示该短语属于哪个列表的反馈。

到目前为止,程序处于无限循环中,并计算总共输入了多少表达式,然后计算某个列表中某事发生了多少次。

if text in access:
    accessno +=1
    counter +=1
    print ('This could be classed as speech act 1: Access')
    print ("number of access hits ", accessno)
    print ("number of total hits ", counter)

所以我的问题是:如何让程序计算用户输入的句子中有多少单词?

任何帮助将不胜感激!

【问题讨论】:

  • 如果您认为以下任何答案为您提供了解决方案,请将其标记为已接受。
  • 由于我是新来的,它不会允许我!但是谢谢你,你帮了很多忙! :)
  • 您可以将自己问题的答案标记为已接受,位于答案左上角的数字附近。问题解决后您的编辑改变了您的问题太多,我会将其恢复为原始状态,cmets 应作为 cmets,而不是在您的问题中,如果您必须将其包含在您的问题中,请将其添加到底部在不改变原意的情况下进行编辑。

标签: python python-3.x counter


【解决方案1】:

你可以通过以下简单的方式做到这一点。

s = input()
# input() is a function that gets input from the user
len(s.split())
# len() checks the length of a list, s.split() splits the users input into a word list.

链接:

input() len() split()


例子:

>>> s = input()
"hello world"
>>> s
'hello world'
>>> s.split()
['hello', 'world']
>>> len(s.split())
2

奖励:一行完成所有操作!

print('You wrote {} words!'.format(len(input("Enter some text, I will tell you how many words you wrote!: ").split())))

【讨论】:

  • 看起来 OP 正在使用 Python 3(print 是给定代码中的函数,而不是语句),因此您可以改用 input()
  • 啊,这么简单!我让用户输入了当前的代码 print ('Hello, Welcome to the chat log assistant') text = input('Please enter your text:') 是的 Python 3
  • @Volatility 除非 OP 确认,否则您永远无法确定,它仍然是有效的 Python 2 代码,但是 OP 很可能使用 Python 3
  • input()raw_input() 更好:它表明需要一个字符串(input() 解释字符串)。另外,input("") 写成input() 更简单自然,因为没有输入提示(最好写成raw_input())。
  • @InbarRose:我的错,你是对的,我错过了 Python 3 标签。 +1。
【解决方案2】:
name = input ()
print len(name)

【讨论】:

  • 这将给出整个字符串的长度,而不是单词的数量。
  • 天哪,我要睡觉了。
  • 这是一种享受: print ('Hello, Welcome to the chat log assistant') text = input('请输入您的文字:') len(text.split()) print ("You已输入 " + text ) if text in access: print ("total number of words" ,len(text.split())) 干杯,伙计们!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
  • 2014-12-30
相关资源
最近更新 更多