Hướng dẫn how do you get a specific word from a string in python? - làm cách nào để lấy một từ cụ thể từ một chuỗi trong python?

Đôi khi chúng ta đi qua các tình huống mà chúng ta yêu cầu để có được tất cả các từ có trong chuỗi, đây có thể là một nhiệm vụ tẻ nhạt được thực hiện bằng phương pháp gốc. Do đó có tốc ký để thực hiện nhiệm vụ này luôn hữu ích. Ngoài ra, bài viết này cũng bao gồm các trường hợp trong đó các dấu chấm câu phải bị bỏ qua. Phương pháp nếu người ta muốn hoàn thành nhiệm vụ cụ thể này. Nhưng nhược điểm là nó thất bại trong các trường hợp chuỗi chứa dấu chấm câu. & NBSP;
Method #1 : Using split() 
Using the split function, we can split the string into a list of words and this is the most generic and recommended method if one wished to accomplish this particular task. But the drawback is that it fails in cases the string contains punctuation marks.
 

Python3

if 'seek' in 'those who seek shall find':
    print('Success!')
7
if 'seek' in 'those who seek shall find':
    print('Success!')
8
if 'seek' in 'those who seek shall find':
    print('Success!')
9

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
0
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
1
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
2 ________ 33 & nbsp;
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
4

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
5
if 'seek' in 'those who seek shall find':
    print('Success!')
8
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
7

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
0
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
1
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
0 ________ 33 & nbsp;
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
2
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
3

Đầu ra: & nbsp; chuỗi gốc là: geeksforgeek là cổng thông tin khoa học máy tính tốt nhất & nbsp; danh sách các từ là: [' ; 
The original string is : Geeksforgeeks is best Computer Science Portal 
The list of words is : [‘Geeksforgeeks’, ‘is’, ‘best’, ‘Computer’, ‘Science’, ‘Portal’] 
 

& nbsp; & nbsp; Phương pháp #2: Sử dụng regex (findall ()) & nbsp; Trong các trường hợp chứa tất cả các ký tự đặc biệt và dấu chấm câu, như đã thảo luận ở trên, phương pháp tìm kiếm thông thường Biểu thức để thực hiện nhiệm vụ này. Hàm Findall Trả về danh sách sau khi lọc chuỗi và trích xuất các từ bỏ qua các dấu chấm câu. & nbsp;
Method #2 : Using regex( findall() ) 
In the cases which contain all the special characters and punctuation marks, as discussed above, the conventional method of finding words in string using split can fail and hence requires regular expressions to perform this task. findall function returns the list after filtering the string and extracting words ignoring punctuation marks.
 

Python3

def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
4
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
5

if 'seek' in 'those who seek shall find':
    print('Success!')
7
if 'seek' in 'those who seek shall find':
    print('Success!')
8
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
8

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
0
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
1
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
2 ________ 33 & nbsp;
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
4

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
5
if 'seek' in 'those who seek shall find':
    print('Success!')
8
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
7

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
0
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
1
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
0 ________ 33 & nbsp;
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
2
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
3

Đầu ra: & nbsp; chuỗi gốc là: geeksforgeek là cổng thông tin khoa học máy tính tốt nhất & nbsp; danh sách các từ là: [' ; 
The original string is : Geeksforgeeks, is best @# Computer Science Portal.!!! 
The list of words is : [‘Geeksforgeeks’, ‘is’, ‘best’, ‘Computer’, ‘Science’, ‘Portal’] 
 

& nbsp; & nbsp; Phương pháp #2: Sử dụng regex (findall ()) & nbsp; Trong các trường hợp chứa tất cả các ký tự đặc biệt và dấu chấm câu, như đã thảo luận ở trên, phương pháp tìm kiếm thông thường Biểu thức để thực hiện nhiệm vụ này. Hàm Findall Trả về danh sách sau khi lọc chuỗi và trích xuất các từ bỏ qua các dấu chấm câu. & nbsp;
Method #3 : Using regex() + string.punctuation 
This method also used regular expressions, but string function of getting all the punctuations is used to ignore all the punctuation marks and get the filtered result string.
 

Python3

def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
4
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
5

if 'seek' in 'those who seek shall find':
    print('Success!')
7
if 'seek' in 'those who seek shall find':
    print('Success!')
8
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
8

if 'seek' in 'those who seek shall find':
    print('Success!')
7
if 'seek' in 'those who seek shall find':
    print('Success!')
8
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
8

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
0
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
1
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
2 ________ 33 & nbsp;
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
4

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
5
if 'seek' in 'those who seek shall find':
    print('Success!')
8
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
7

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
0
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
1
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
0 ________ 33 & nbsp;
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
2
def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False
3

Đầu ra: & nbsp; chuỗi gốc là: geeksforgeek là cổng thông tin khoa học máy tính tốt nhất & nbsp; danh sách các từ là: [' ; 
The original string is : Geeksforgeeks, is best @# Computer Science Portal.!!! 
The list of words is : [‘Geeksforgeeks’, ‘is’, ‘best’, ‘Computer’, ‘Science’, ‘Portal’] 
 


230

Bạn chỉ có thể thêm một khoảng trống trước và sau "từ".
Learn more.

Bằng cách này, nó tìm kiếm không gian trước và sau "từ".

Đã trả lời ngày 26 tháng 2 năm 2015 lúc 14:23

if string.find(word):
    print("success")

Hướng dẫn how do you get a specific word from a string in python? - làm cách nào để lấy một từ cụ thể từ một chuỗi trong python?

mkrieger1

Pyguypyguy4 gold badges46 silver badges57 bronze badges

hỏi ngày 16 tháng 3 năm 2011 lúc 1:10Mar 16, 2011 at 1:10

Hướng dẫn how do you get a specific word from a string in python? - làm cách nào để lấy một từ cụ thể từ một chuỗi trong python?

1

Co chuyện gi sai vơi:

if word in mystring: 
   print('success')

Martin Thoma

113K148 Huy hiệu vàng573 Huy hiệu bạc877 Huy hiệu đồng148 gold badges573 silver badges877 bronze badges

Đã trả lời ngày 16 tháng 3 năm 2011 lúc 1:13Mar 16, 2011 at 1:13

FabriziomfabriziomfabrizioM

44,9K15 Huy hiệu vàng98 Huy hiệu bạc115 Huy hiệu đồng15 gold badges98 silver badges115 bronze badges

13

if 'seek' in 'those who seek shall find':
    print('Success!')

Nhưng hãy nhớ rằng điều này phù hợp với một chuỗi các ký tự, không nhất thiết là toàn bộ từ - ví dụ,

def find_words(text, search):
    """Find exact words"""
    dText   = text.split()
    dSearch = search.split()

    found_word = 0

    for text_word in dText:
        for search_word in dSearch:
            if search_word == text_word:
                found_word += 1

    if found_word == len(dSearch):
        return lenSearch
    else:
        return False
4 là đúng. Nếu bạn chỉ muốn khớp với toàn bộ từ, bạn nên sử dụng các biểu thức thông thường:

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None

Đã trả lời ngày 16 tháng 3 năm 2011 lúc 1:52Mar 16, 2011 at 1:52

Hugh Bothwellhugh BothwellHugh Bothwell

53,8K7 Huy hiệu vàng81 Huy hiệu bạc98 Huy hiệu Đồng7 gold badges81 silver badges98 bronze badges

6

Nếu bạn muốn tìm hiểu xem toàn bộ một từ có nằm trong danh sách các từ được phân tách không gian hay không, chỉ cần sử dụng:

def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False

Phương pháp thanh lịch này cũng là nhanh nhất. So với cách tiếp cận của Hugh Bothwell và Dasong:

>python -m timeit -s "def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 0.351 usec per loop

>python -m timeit -s "import re" -s "def contains_word(s, w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search(s)" "contains_word('the quick brown fox', 'brown')"
100000 loops, best of 3: 2.38 usec per loop

>python -m timeit -s "def contains_word(s, w): return s.startswith(w + ' ') or s.endswith(' ' + w) or s.find(' ' + w + ' ') != -1" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 1.13 usec per loop

Chỉnh sửa: Một biến thể nhỏ về ý tưởng này cho Python 3.6+, nhanh không kém: A slight variant on this idea for Python 3.6+, equally fast:

def contains_word(s, w):
    return f' {w} ' in f' {s} '

Đã trả lời ngày 11 tháng 4 năm 2016 lúc 20:32Apr 11, 2016 at 20:32

user200783user200783user200783

13.3k11 Huy hiệu vàng63 Huy hiệu bạc125 Huy hiệu Đồng11 gold badges63 silver badges125 bronze badges

6

Tìm trả về một số nguyên đại diện cho chỉ số nơi tìm thấy mục tìm kiếm. Nếu nó không được tìm thấy, nó sẽ trả về -1.

haystack = 'asdf'

haystack.find('a') # result: 0
haystack.find('s') # result: 1
haystack.find('g') # result: -1

if haystack.find(needle) >= 0:
  print('Needle found.')
else:
  print('Needle not found.')

Martin Thoma

113K148 Huy hiệu vàng573 Huy hiệu bạc877 Huy hiệu đồng148 gold badges573 silver badges877 bronze badges

Đã trả lời ngày 16 tháng 3 năm 2011 lúc 1:13Mar 16, 2011 at 1:13

FabriziomfabriziomMatt Howell

44,9K15 Huy hiệu vàng98 Huy hiệu bạc115 Huy hiệu đồng7 gold badges47 silver badges56 bronze badges

0

Nhưng hãy nhớ rằng điều này phù hợp với một chuỗi các ký tự, không nhất thiết là toàn bộ từ - ví dụ,

def find_words(text, search):
    """Find exact words"""
    dText   = text.split()
    dSearch = search.split()

    found_word = 0

    for text_word in dText:
        for search_word in dSearch:
            if search_word == text_word:
                found_word += 1

    if found_word == len(dSearch):
        return lenSearch
    else:
        return False
4 là đúng. Nếu bạn chỉ muốn khớp với toàn bộ từ, bạn nên sử dụng các biểu thức thông thường:

if word in string.split():
    print("success")

Martin Thoma

113K148 Huy hiệu vàng573 Huy hiệu bạc877 Huy hiệu đồng148 gold badges573 silver badges877 bronze badges

Đã trả lời ngày 16 tháng 3 năm 2011 lúc 1:13Dec 1, 2016 at 18:26

FabriziomfabriziomCorvax

44,9K15 Huy hiệu vàng98 Huy hiệu bạc115 Huy hiệu đồng7 silver badges12 bronze badges

3

Nhưng hãy nhớ rằng điều này phù hợp với một chuỗi các ký tự, không nhất thiết là toàn bộ từ - ví dụ,

def find_words(text, search):
    """Find exact words"""
    dText   = text.split()
    dSearch = search.split()

    found_word = 0

    for text_word in dText:
        for search_word in dSearch:
            if search_word == text_word:
                found_word += 1

    if found_word == len(dSearch):
        return lenSearch
    else:
        return False
4 là đúng. Nếu bạn chỉ muốn khớp với toàn bộ từ, bạn nên sử dụng các biểu thức thông thường:

Đã trả lời ngày 16 tháng 3 năm 2011 lúc 1:52

def find_words(text, search):
    """Find exact words"""
    dText   = text.split()
    dSearch = search.split()

    found_word = 0

    for text_word in dText:
        for search_word in dSearch:
            if search_word == text_word:
                found_word += 1

    if found_word == len(dSearch):
        return lenSearch
    else:
        return False

usage:

if word in mystring: 
   print('success')
0

Hugh Bothwellhugh BothwellJun 22, 2012 at 22:51

53,8K7 Huy hiệu vàng81 Huy hiệu bạc98 Huy hiệu ĐồngGuray Celik

Nếu bạn muốn tìm hiểu xem toàn bộ một từ có nằm trong danh sách các từ được phân tách không gian hay không, chỉ cần sử dụng:1 gold badge14 silver badges13 bronze badges

0

def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')

contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False

if word in mystring: 
   print('success')
1

Phương pháp thanh lịch này cũng là nhanh nhất. So với cách tiếp cận của Hugh Bothwell và Dasong:

Chỉnh sửa: Một biến thể nhỏ về ý tưởng này cho Python 3.6+, nhanh không kém:

Đã trả lời ngày 11 tháng 4 năm 2016 lúc 20:329 gold badges57 silver badges81 bronze badges

13.3k11 Huy hiệu vàng63 Huy hiệu bạc125 Huy hiệu ĐồngJun 15, 2012 at 7:23

Tìm trả về một số nguyên đại diện cho chỉ số nơi tìm thấy mục tìm kiếm. Nếu nó không được tìm thấy, nó sẽ trả về -1.daSong

haystack = 'asdf'

haystack.find('a') # result: 0
haystack.find('s') # result: 1
haystack.find('g') # result: -1

if haystack.find(needle) >= 0:
  print('Needle found.')
else:
  print('Needle not found.')
1 gold badge5 silver badges9 bronze badges

1

Matt Howellmatt Howell

15.4K7 Huy hiệu vàng47 Huy hiệu bạc56 Huy hiệu Đồngsplit(separator, num) method for that. It returns a list of all the words in the string, using separator as the separator. If separator is unspecified it splits on all whitespace (optionally you can limit the number of splits to num).

if word in mystring: 
   print('success')
2

Bạn có thể chia chuỗi thành các từ và kiểm tra danh sách kết quả.

if word in mystring: 
   print('success')
3

Đã trả lời ngày 1 tháng 12 năm 2016 lúc 18:26separator argument like this:

if word in mystring: 
   print('success')
4

Martin Thoma

113K148 Huy hiệu vàng573 Huy hiệu bạc877 Huy hiệu đồng148 gold badges573 silver badges877 bronze badges

CorvaxcorvaxDec 18, 2017 at 11:44

7547 Huy hiệu bạc12 Huy hiệu đồngtstempko

Hàm nhỏ này so sánh tất cả các từ tìm kiếm trong văn bản đã cho. Nếu tất cả các từ tìm kiếm được tìm thấy trong văn bản, trả về độ dài của tìm kiếm hoặc

def find_words(text, search):
    """Find exact words"""
    dText   = text.split()
    dSearch = search.split()

    found_word = 0

    for text_word in dText:
        for search_word in dSearch:
            if search_word == text_word:
                found_word += 1

    if found_word == len(dSearch):
        return lenSearch
    else:
        return False
5 nếu không.1 gold badge14 silver badges16 bronze badges

2

Cũng hỗ trợ tìm kiếm chuỗi Unicode.

if word in mystring: 
   print('success')
5

Đã trả lời ngày 22 tháng 6 năm 2012 lúc 22:51

Guray Celikguray CelikAug 9, 2017 at 10:11

1.2751 Huy hiệu vàng14 Huy hiệu bạc13 Huy hiệu đồngMartin Thoma

113K148 Huy hiệu vàng573 Huy hiệu bạc877 Huy hiệu đồng148 gold badges573 silver badges877 bronze badges

Nếu khớp một chuỗi các ký tự là không đủ và bạn cần phải khớp với toàn bộ từ, thì đây là một chức năng đơn giản để hoàn thành công việc. Về cơ bản, nó nối các không gian khi cần thiết và tìm kiếm điều đó trong chuỗi:

if word in mystring: 
   print('success')
6

Martin Thoma

113K148 Huy hiệu vàng573 Huy hiệu bạc877 Huy hiệu đồng148 gold badges573 silver badges877 bronze badges

Điều này giả định rằng dấu phẩy và các dấu chấm câu khác đã bị loại bỏ.Nov 2, 2016 at 8:39

Hướng dẫn how do you get a specific word from a string in python? - làm cách nào để lấy một từ cụ thể từ một chuỗi trong python?

IANSRameez

15.2k9 Huy hiệu vàng57 Huy hiệu bạc81 Huy hiệu Đồng5 silver badges11 bronze badges

Đã trả lời ngày 15 tháng 6 năm 2012 lúc 7:23

if word in mystring: 
   print('success')
7

Dasongdasong

if word in mystring: 
   print('success')
8

4071 Huy hiệu vàng5 Huy hiệu bạc9 Huy hiệu đồng

if word in mystring: 
   print('success')
9

Sample:

if 'seek' in 'those who seek shall find':
    print('Success!')
0

Sử dụng Regex là một giải pháp, nhưng nó quá phức tạp cho trường hợp đó.

Bạn chỉ có thể chia văn bản thành danh sách các từ. Sử dụng phương pháp tách (dấu phân cách, num) cho điều đó. Nó trả về một danh sách tất cả các từ trong chuỗi, sử dụng dấu phân cách làm dấu phân cách. Nếu dấu tách không xác định, nó chia tách trên tất cả khoảng trắng (tùy chọn bạn có thể giới hạn số lượng phân tách thành Num).Dec 26, 2020 at 5:18

Điều này sẽ không hoạt động cho chuỗi với dấu phẩy, v.v. Ví dụ:marcio

Nếu bạn cũng muốn phân chia trên tất cả các dấu phẩy, v.v. Sử dụng đối số phân tách như sau:5 silver badges16 bronze badges

Đã trả lời ngày 18 tháng 12 năm 2017 lúc 11:44

if 'seek' in 'those who seek shall find':
    print('Success!')
1

Tstempkotstempko

if 'seek' in 'those who seek shall find':
    print('Success!')
2

Martin Thoma

113K148 Huy hiệu vàng573 Huy hiệu bạc877 Huy hiệu đồng148 gold badges573 silver badges877 bronze badges

1.1761 Huy hiệu vàng14 Huy hiệu bạc16 Huy hiệu đồngFeb 26, 2015 at 14:23

Khi bạn đang yêu cầu một từ và không phải cho một chuỗi, tôi muốn trình bày một giải pháp không nhạy cảm với tiền tố / hậu tố và bỏ qua trường hợp:PyGuy

Nếu lời nói của bạn có thể chứa các ký tự đặc biệt của Regex (chẳng hạn như

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> 
findWholeWord('word')('swordsmith')                   # -> None
3), thì bạn cần
def find_words(text, search):
    """Find exact words"""
    dText   = text.split()
    dSearch = search.split()

    found_word = 0

    for text_word in dText:
        for search_word in dSearch:
            if search_word == text_word:
                found_word += 1

    if found_word == len(dSearch):
        return lenSearch
    else:
        return False
73 bronze badges

1

Đã trả lời ngày 9 tháng 8 năm 2017 lúc 10:11

Martin Thomamartin Thoma

if 'seek' in 'those who seek shall find':
    print('Success!')
3

Martin Thoma

113K148 Huy hiệu vàng573 Huy hiệu bạc877 Huy hiệu đồng148 gold badges573 silver badges877 bronze badges

Cách nâng cao để kiểm tra từ chính xác mà chúng ta cần tìm trong một chuỗi dài:Aug 25, 2021 at 13:25

Đã trả lời ngày 2 tháng 11 năm 2016 lúc 8:39Milos Cuculovic

Rameezrameez50 gold badges156 silver badges264 bronze badges

5345 huy hiệu bạc11 huy hiệu đồng

if 'seek' in 'those who seek shall find':
    print('Success!')
4

Để đếm số lần xuất hiện của một từ trong một chuỗi:

if 'seek' in 'those who seek shall find':
    print('Success!')
5

trả về 1

if 'seek' in 'those who seek shall find':
    print('Success!')
6

trả về 1

Sử dụng hàm trong 'if' để kiểm tra xem từ có tồn tại trong một chuỗi không

Đã trả lời ngày 18 tháng 3 lúc 9:37Mar 18 at 9:37

IstuartistuartiStuart

3362 Huy hiệu bạc6 Huy hiệu Đồng2 silver badges6 bronze badges

Làm cách nào để trích xuất một từ cụ thể từ một chuỗi trong Python?

Phương pháp số 1: Sử dụng split () Sử dụng hàm chia, chúng ta có thể chia chuỗi thành một danh sách các từ và đây là phương thức chung và được đề xuất nhất nếu người ta muốn hoàn thành nhiệm vụ cụ thể này.Using split() Using the split function, we can split the string into a list of words and this is the most generic and recommended method if one wished to accomplish this particular task.

Làm cách nào để tìm thấy một văn bản cụ thể trong một chuỗi python?

Chuỗi tìm () trong python chỉ cần gọi phương thức trên đối tượng chuỗi để tìm kiếm một chuỗi, như vậy: obj.find (tìm kiếm tìm kiếm).Phương thức Find () tìm kiếm một chuỗi truy vấn và trả về vị trí ký tự nếu được tìm thấy.Nếu chuỗi không được tìm thấy, nó sẽ trả về -1.obj. find(“search”). The find() method searches for a query string and returns the character position if found. If the string is not found, it returns -1.

Làm cách nào để trích xuất một phần cụ thể của chuỗi trong Python?

Nhận một chuỗi con của một chuỗi đang trích xuất một phần của chuỗi từ một đối tượng chuỗi.Nó cũng được gọi là một hoạt động cắt lát.Bạn có thể nhận được chuỗi con của một chuỗi trong Python bằng tùy chọn STR [0: N].using the str[0:n] option.

Làm cách nào để trích xuất một từ duy nhất từ một chuỗi?

Để có được từ đầu tiên của một chuỗi: gọi phương thức chia (), chuyển nó, một chuỗi chứa một khoảng trống dưới dạng tham số.Phương thức phân chia sẽ trả về một mảng chứa các từ trong chuỗi.Truy cập mảng tại chỉ mục 0 để có được từ đầu tiên của chuỗi.Call the split() method passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Access the array at index 0 to get the first word of the string.