【问题标题】:Trying to make function which takes string as input and returns no. of words in whole string试图制作将字符串作为输入并返回 no 的函数。整个字符串中的单词
【发布时间】:2021-01-25 08:36:27
【问题描述】:

**它将 Input 作为这样的字符串 - 'Nice one' 并且输出给出 - 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

【问题讨论】:

  • 'Nice one' 中有 2 个单词。我认为您的意思是“输出字符串中单词的长度”。

标签: lua


【解决方案1】:

您可以根据您的新要求找到一个简单的替代方案:

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

【讨论】:

  • 我想计算整个字符串中单词中的字符以及来自用户的字符串传递,例如用户传递。 'I am a boy' 然后根据单词中的字符给出 1,2,1,3。
  • 我又更新了一次,基本上就是按你说的做。该代码可能是高效的,因为它不会创建中间字符串或无用数据。如果您有兴趣,可以阅读有关表演的更多信息,尤其是 table.insert:stackoverflow.com/questions/154672/…
【解决方案2】:
def countLenWords(s):
   s=s.split(" ")
   s=map(len,s)
   s=map(str,s)
   s=list(s)
   return s

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

s=s.split(" ") 用分隔符“”(空格)分割字符串 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(" "))))

【讨论】:

  • 我想计算整个字符串中单词中的字符以及来自用户的字符串传递,例如用户传递。 'I am a boy' 然后根据单词中的字符给出 1,2,1,3。
  • @Dxx 以字符串或列表的形式返回值?修改后的答案以列表形式返回
【解决方案3】:
-- 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):
    • [] 是一个字符类:一组字符。它匹配括号内的任何内容,例如[ab] 将匹配 ab
    • %l 是任何小写拉丁字母,
    • %u 是任何大写拉丁字母,
    • + 表示一个或多个重复。

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

【讨论】:

  • 这正是我想要的,但是 [%l%u]+ 有什么用,我不明白你说的是什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
  • 2023-02-15
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多