试图创建一个函数,该函数以字符串为输入,并返回整个字符串中的单词数



**它将Input作为一个字符串,例如"不错"Output给出-4,3(这是句子或字符串中的单词数(**

function countx(str)
local count = {}
for i = 1, string.len(str) do
s = ''
while (i<=string.len(str) and string.sub(str, i, i) ~= ' ' ) do
s = s .. string.sub(str, i, i)
i = i+1
end
if (string.len(s)>0) then
table.insert(count,string.len(s))
end
end
return table.concat(count, ',')
end

您可以为您的新需求找到一个简单的替代方案:

function CountWordLength (String)
local Results  = { }
local Continue = true
local Position = 1
local SpacePosition

while Continue do
SpacePosition = string.find(String, " ", Position)
if SpacePosition then
Results[#Results + 1] = SpacePosition - Position
Position = SpacePosition + 1
-- if needed to print the string
-- local SubString = String:sub(Position, SpacePosition)
-- print(SubString)
else
Continue = false
end    
end
Results[#Results + 1] = #String - Position + 1

return Results  
end
Results = CountWordLength('I am a boy')
for Index, Value in ipairs(Results) do
print(Value)
end

得出以下结果:

1
2
1
3
def countLenWords(s):
s=s.split(" ")
s=map(len,s)
s=map(str,s)
s=list(s)
return s

上述函数返回一个列表,其中包含每个单词中的字符数

CCD_ 1用分隔符分割字符串"(空格(s=map(len,s)将单词映射为int中单词的长度s=map(str,s)将值映射为字符串s=list(s)map对象转换为list

上述功能的简短版本(一行所有(

def countLenWords(s):
return list(map(str,map(len,s.split(" "))))
-- Localise for performance.
local insert = table.insert
local text = 'I am a poor boy straight. I do not need sympathy'
local function word_lengths (text)
local lengths = {}
for word in text:gmatch '[%l%u]+' do
insert (lengths, word:len())
end
return lengths
end
print ('{' .. table.concat (word_lengths (text), ', ') .. '}')
  • gmatch在字符串中的模式匹配上返回迭代器
  • [%l%u]+是Lua正则表达式(请参见http://lua-users.org/wiki/PatternsTutorial)至少匹配一个小写或大写字母:
    • []字符类:一组字符。它匹配括号内的任何内容(例如s=s.split(" ")0将同时匹配ab(
    • CCD_ 13是任何小写拉丁字母
    • CCD_ 14是任何大写的拉丁字母
    • CCD_ 15表示一个或多个重复

因此,text:gmatch '[%l%u]+'将返回一个迭代器,该迭代器将逐个生成由拉丁字母组成的单词,直到text结束。此迭代器用于通用for(请参阅https://www.lua.org/pil/4.3.5.html);并且在任何迭代中CCD_ 19将包含正则表达式的完全匹配。

相关内容

最新更新