简体   繁体   中英

all unique permutations of the tokens

Output all unique permutations of the tokens from part 1. And the total number of permutations.

Example:

  • This is a test
  • This is test a
  • This a is test
  • This test is a
  • This test a is
  • Test is a This

do you know how to do it in python?

import itertools
import itertools
from nltk.tokenize import word_tokenize
import nltk
nltk.download('punkt')
def tokenize_word():
  sentence = str(input("please right a comment: "))
  punctuation = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
 
# Removing punctuations in string
# Using loop + punctuation string
  for element in sentence:
    if element in punctuation:
        sentence = sentence.replace(element, "")
  
  tokenize_sentence= word_tokenize(sentence)
  alphabetics_order_sentence = sorted(tokenize_sentence)
  for i in range(1, len(alphabetics_order_sentence) + 1):
    permutations= itertools.permutations(alphabetics_order_sentence)
    print(permutations)

tokenize_word()

You can use the function permutations from the package itertools (if package is allowed).

from itertools import permutations

st = "This is a test"
result = list(permutations(st.split()))

for i in result:
    print(" ".join(i))
    
print()
print("The number of permutations is {}".format(len(result)))

Output from code above:

This is a test
This is test a
This a is test
This a test is
This test is a
This test a is
is This a test
is This test a
is a This test
is a test This
is test This a
is test a This
a This is test
a This test is
a is This test
a is test This
a test This is
a test is This
test This is a
test This a is
test is This a
test is a This
test a This is
test a is This

The number of permutations is 24

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM