我正在尝试返回序列中字符串中以大写字母或标题大小写开头的所有单词的列表。
例如,在字符串John Walker Smith is currently in New York
中,我想返回如下列表:
['John Walker Smith', 'New York']
我的代码仅在有两个标题词时才有效。如何扩展它以在序列中拾取两个以上的标题词。
def get_composite_names(s):
l = [x for x in s.split()]
nouns = []
for i in range(0,len(l)):
if i > len(l)-2:
break
if l[i] == l[i].title() and l[i+1] == l[i+1].title():
temp = l[i]+' '+l[i+1]
nouns.append(temp)
return nouns
答案 0 :(得分:6)
这是在没有正则表达式的情况下完成此任务的一种方法:
from itertools import groupby
string = "John Walker Smith is currently in New York"
groups = []
for key, group in groupby(string.split(), lambda x: x[0].isupper()):
if key:
groups.append(' '.join(list(group)))
print groups
# ['John Walker Smith', 'New York']
答案 1 :(得分:0)
在while循环中,当我们看到标题字词时,我们会将其添加到列表 load=function(){
this.http.get('http://localhost:8000/load').subscribe(data => {
// Read the result field from the JSON response.
this.rows=JSON.parse(data["_body"]);
}); } <p-dataTable [value]="rows">
<p-column field="id" header="ID"></p-column>
<p-column field="username" header="Name of Person who sent HI"></p-column>
<p-column field="datetime" header="Datetime"></p-column>
</p-dataTable>
中。
当我们遇到一个非标题词时,我们添加标题词(如果它不为空),并重置server.route({
method: 'GET',
path: '/load',
handler: function(request, reply) {
connection.query("SELECT * FROM hi ", function(error, results, fields) {
if (error) throw error;
return reply(JSON.stringify(results));
});
}});
列表。
words
答案 2 :(得分:0)
这似乎粗略地做了你想要的,它保留了标点符号和一个字母的单词。我不确定这是不是你想要的,但希望这段代码能给你一个很好的起点,让它做你想要的,如果不是的话。
def get_composite_names(s):
l = [x for x in s.split()]
nouns = []
current_title = None
for i in range(0, len(l)):
if l[i][0].isupper():
if (current_title is not None):
current_title = " ".join((current_title, l[i]))
else:
current_title = l[i]
else:
if (current_title is not None):
nouns.append(current_title)
current_title = None
if (current_title is not None):
nouns.append(current_title)
current_title = None
return nouns
print(get_composite_names("Hello World my name is John Doe"))
#returns ['Hello World', 'John Doe']
print(get_composite_names("I live in Halifax."))
#returns ['I', 'Halifax.']
print(get_composite_names("Even old New York was once New Amsterdam"))
#returns ['Even', 'New York', 'New Amsterdam']
答案 3 :(得分:0)
它并不完美(而且我对Regex很糟糕)但是我确实设法生成了这个与您正在寻找的匹配的正则表达式:
(?:(?:[A-Z]{1}[a-z]*)(?:$|\s))+
鉴于字符串“约翰沃克史密斯目前在纽约他感觉很棒”将匹配“约翰沃克史密斯”,“纽约”和“伟大”
有人可能会攻击我的正则表达式 - 随意修改这个答案