计算用空格

时间:2017-09-21 17:16:00

标签: python

Python中的

我希望用户使用Input参数键入一个句子。

zin = input("Typ een zinnetje: ")

在一个函数中,我想要计算所有单词(用空格分隔的所有单词)。 我该怎么做?

这是我到目前为止所做的。

zin = input("Typ een zinnetje: ")
def gemiddelde():
    aantal = zin.count(zin)
    return aantal

print (gemiddelde())

无论如何都打印1。

6 个答案:

答案 0 :(得分:4)

split将按空格分隔字符串,len将返回长度:

zin = input("Typ een zinnetje: ")
def gemiddelde():
    aantal = len(zin.split())
    return aantal

print (gemiddelde())

答案 1 :(得分:4)

您需要按空格分割句子,然后使用len

zin = raw_input("Typ een zinnetje: ")
def gemiddelde():
    aantal = len(zin.split(' '))
    return aantal

print (gemiddelde())

答案 2 :(得分:1)

zin = input("Typ een zinnetje: ")
def gemiddelde():
        aantal = zin.split(" ")
        return aantal.__len__()

print (gemiddelde())

答案 3 :(得分:0)

除了我之前的答案之外,split会在每次出现空格时分割字符串,这意味着如果存在双空格或前导/尾随空格等内容,它可能会读取更多单词。可能值得做一些快速检查,以确保你得到的实际上是单词的数量。

zin = input("Typ een zinnetje: ")

def gemiddelde():
    aantal = zin.split(" ")
    num = sum(len(x) > 0 for x in aantal)
    return num

print (gemiddelde())

答案 4 :(得分:0)

单行,

//get canvas/context
const canvas = document.getElementById("myCanvas")
const context = canvas.getContext("2d")

//create your shape data in a Path2D object
const path = new Path2D()
path.rect(250, 350, 200, 100)
path.rect(25,72,32,32)
path.closePath()

//draw your shape data to the context
context.fillStyle = "#FFFFFF"
context.fillStyle = "rgba(225,225,225,0.5)"
context.fill(path)
context.lineWidth = 2
context.strokeStyle = "#000000"
context.stroke(path)

function getXY(canvas, event){ //adjust mouse click to canvas coordinates
  const rect = canvas.getBoundingClientRect()
  const y = event.clientY - rect.top
  const x = event.clientX - rect.left
  return {x:x, y:y}
}

document.addEventListener("click",  function (e) {
  const XY = getXY(canvas, e)
  //use the shape data to determine if there is a collision
  if(context.isPointInPath(path, XY.x, XY.y)) {
    // Do Something with the click
    alert("clicked in rectangle")
  }
}, false)

def count_words(s): return len(s.split()) 函数会将split()拆分为string s,其中拆分的分隔符为list of wordswhitespace将返回分割字符串时获得的元素数。

答案 5 :(得分:0)

zin = input("Typ een zinnetje: ")

def gemiddelde(s):
    return len(s.split(' '))

print (gemiddelde(zin))
相关问题