编写一个程序,从输入的一串字符中找出连续字母组成的单词,并将这些单词组成列表后显示;(不用正则表达式)
时间: 2024-05-09 19:16:26 浏览: 39
下面是一个基本的实现,它基于空格分隔单词,并假设输入没有标点符号和数字:
```python
def find_words(text):
words = []
current_word = ""
for char in text:
if char.isalpha():
current_word += char
else:
if current_word:
words.append(current_word)
current_word = ""
if current_word:
words.append(current_word)
return words
text = "Hello world! This is a test."
words = find_words(text)
print(words)
```
输出:
```
['Hello', 'world', 'This', 'is', 'a', 'test']
```
这个程序遍历输入中的每个字符,如果字符是字母,则将其添加到当前单词中。如果字符不是字母,则将当前单词添加到单词列表中,并将当前单词重置为空字符串。最后,如果最后一个单词不是由标点符号或空格分隔的,则将其添加到单词列表中。
相关问题
编写一个函数maxword(s),用以找出已知字符串s中的最长单词。
题目要求编写一个函数maxword(s),用以找出已知字符串s中的最长单词。
具体实现思路可能是:
1. 首先将字符串s按照空格分隔成一个单词列表words,可以使用split函数。
2. 设定一个最长单词长度变量max_len,初值为0。
3. 遍历单词列表words,对于每一个单词,如果其长度大于max_len,则将max_len更新为当前单词长度,并将当前单词保存到max_word变量中。
4. 返回找到的最长单词max_word。
一个简单的Python实现如下:
```python
def maxword(s):
words = s.split()
max_len = 0
max_word = ''
for word in words:
if len(word) > max_len:
max_len = len(word)
max_word = word
return max_word
```
调用该函数:
```python
s = 'This is a sample sentence to test the function.'
result = maxword(s)
print(result) # 输出:function.
```
注意,在本题中需要处理的字符串仅包含空格和字母等字符,如果涉及到更复杂的字符串处理,可能需要考虑更多的边界情况。
编写一个程序使从键盘输入一串字符,找出这串字符中有多少个字母a或A打头的英文单词,并将开始位置的索引下标和结束位置之后的索引下标构成一个位置元组,将这些英文单词的位置元组形成的列表作为结果显示。 例如:输入An apple a day keeps the doctor away. 一日一个苹果,身体健康不求医。 结果显示为:[(0, 2), (3, 8), (9, 10), (32, 36)]
好的,这是一个 Python 程序,可以实现你的需求:
```python
import re
input_string = input("请输入一串字符:")
pattern = r'\b([Aa]\w*)\b'
matches = re.finditer(pattern, input_string)
result = []
for match in matches:
result.append((match.start(), match.end() - 1))
print(result)
```
上面的程序中,使用了正则表达式来匹配以字母 a 或 A 开头的英文单词。其中,`\b` 表示单词边界,`\w` 表示匹配任意字母、数字或下划线。
使用 `re.finditer()` 函数可以找到所有匹配的位置,然后依次将其加入到结果列表中。最后输出结果即可。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)