2016-07-05 57 views
2

我需要查找用户输入的句子中单词的位置,并且如果该单词出现多次,只会首次打印该单词出现的单词查找单词出现多次的句子中的原始位置

我有代码,以便远

sentence=input("Enter a sentence: ") 
sentence=sentence.lower() 
words=sentence.split() 
place=[] 

for c,a in enumerate(words): 
    if words.count(a)>2 : 
     place.append(words.index(a+1)) 
    else: 
     place.append(c+1) 

print(sentence) 
print(place) 

但它打印的句子中各个单词的位置,而不是重复出现不止一次

任何一个字的原始位置帮我这个?

+1

你的问题不清楚;也许一个或两个例子会有所帮助。 –

回答

2

如果您使用的是python 2,那么raw_input而不是input否则它会被评估。这不是一个问题,只是一个观察(你可能使用python 3,所以我会离开它)。

您可以创建一个词典来跟踪找到的词数和位置。这基本上是一个列表的字典。字典是一个位置列表中的单词地图。

sentence=input("Enter a sentence: ") 
sentence=sentence.lower() 
words=sentence.split() 

place={} 
for pos, word in enumerate(words): 
    try: 
     place[word].append(pos) 
    except KeyError: 
     place[word] = [pos] 

print(sentence) 
print(place) 

另外,如果你想做一些更先进一点与你的句子解析,你可以这样做:

import re 
words = re.split('\W+',sentence) 

基本上采用全nonalphanumerics(逗号,冒号,等等)上的分裂。请注意,您可以通过这种方式获得空白条目(可能在最后)。

+0

'raw_input'在python3中被删除。 – Arnial

+0

@Arnial啊,我还在用2.7。我会更新。不久的一天,我会与时俱进。谢谢:-) – woot

+0

@woot,我想OP需要一个类似于我答案中的输出。 >>> *但它会打印句子中单个单词的位置,而不是重复出现一次以上单词的原始位置*。你怎么看? – SilentMonk

1

你的代码需要进行一些修改,以达到你正在尝试做的事:

  • if words.count(a)>2:这应该是if words.count(a)>1,因为如果重复字数将超过1。

  • place.append(words.index(a+1)):应该是place.append(words.index(a)+1),因为您想查找a的索引,然后向其中加1。

基于所述建议的修改后的代码:

sentence=input("Enter a sentence: ") 

sentence=sentence.lower() 
words=sentence.split() 
place=[] 


for c,a in enumerate(words): 
    if words.count(a)>1 : 
     place.append(words.index(a)+1) 
    else: 
     place.append(c+1) 

print(sentence) 
print(place) 

输出:

Enter a sentence: "hello world hello people hello everyone" 
hello world hello people hello everyone 
[1, 2, 1, 4, 1, 6] 
0

分割字符串

>>> s = '''and but far and so la ti but''' 
>>> s = s.split() 
>>> s 
['and', 'but', 'far', 'and', 'so', 'la', 'ti', 'but'] 

使用set查找唯一字并使用list.index方法查找每个唯一字的第一个位置。

>>> map(s.index, set(s)) 
[0, 5, 2, 1, 4, 6] 

zip结果是用唯一的单词将单词与其位置相关联。

>>> zip(set(s),map(s.index, set(s))) 
[('and', 0), ('la', 5), ('far', 2), ('but', 1), ('so', 4), ('ti', 6)] 
>>> 

我想一个列表理解可能更容易阅读;

>>> s = '''and but far and so la ti but''' 
>>> s = s.split() 
>>> result = [(word, s.index(word)) for word in set(s)] 
>>> result 
    [('and', 0), ('la', 5), ('far', 2), ('but', 1), ('so', 4), ('ti', 6)] 
>>> 

排序上的位置

>>> import operator 
>>> position = operator.itemgetter(1) 
>>> result.sort(key = position) 
>>> result 
[('and', 0), ('but', 1), ('far', 2), ('so', 4), ('la', 5), ('ti', 6)] 
>>> 
相关问题