工藤  晃

工藤 晃

1661370660

使用 Python Cheatsheet 在基本級別操作和處理字符串

試試這個字符串處理入門備忘單,以了解使用 Python 在基本級別上操作和處理字符串。

字符串處理的重要性

自然語言處理和文本分析是目前研究和應用的熱門領域。這些領域需要各種特定的技能和概念,在進入有意義的實踐之前需要徹底理解。然而,在達到這一點之前,基本的字符串操作和處理是必須的。

在我看來,有兩種不同類型的廣泛的計算字符串處理技能需要學習。其中第一個是正則表達式,一種基於模式的文本匹配方法。可以搜索到許多關於正則表達式的精彩介紹,但視覺學習者可能會欣賞有關該主題的fast.ai 代碼優先自然語言處理介紹課程視頻

另一個獨特的計算字符串處理技能是能夠利用給定編程語言的標準庫進行基本的字符串操作。因此,本文是一個簡短的 Python 字符串處理入門。

請注意,有意義的文本分析遠遠超出了字符串處理,這些更高級技術的核心可能不需要您經常自己操作文本。但是,文本數據處理是成功的文本分析項目中重要且耗時的部分,而上述這些字符串處理技能在這裡將是無價之寶。在基本層面上理解文本的計算處理對於理解更高級的文本分析技術在概念上也非常重要。

以下許多示例都使用了 Python 標準庫字符串模塊,因此方便參考是個好主意。

Python 字符串處理備忘單

這個方便的備忘單包含此可下載 PDF 中的所有代碼。

剝離白斑

去除空格是基本的字符串處理要求。您可以使用lstrip()方法(左)去除前導空格,使用(右)去除尾隨空格rstrip(),以及使用strip().

s = '   This is a sentence with whitespace.       \n'

print('Strip leading whitespace: {}'.format(s.lstrip()))
print('Strip trailing whitespace: {}'.format(s.rstrip()))
print('Strip all whitespace: {}'.format(s.strip()))
Strip leading whitespace: This is a sentence with whitespace.       

Strip trailing whitespace:    This is a sentence with whitespace.
Strip all whitespace: This is a sentence with whitespace.

有興趣剝離除空格以外的字符嗎?相同的方法很有幫助,並通過傳入要剝離的字符來使用。

s = 'This is a sentence with unwanted characters.AAAAAAAA'

print('Strip unwanted characters: {}'.format(s.rstrip('A')))
Strip unwanted characters: This is a sentence with unwanted characters.

format()如有必要,不要忘記查看字符串文檔。

拆分字符串

split()使用該方法在 Python 中將字符串拆分為較小子字符串的列表通常很有用且很容易完成。

s = 'KDnuggets is a fantastic resource'

print(s.split())
['KDnuggets', 'is', 'a', 'fantastic', 'resource']

默認情況下,split()拆分空格,但也可以傳入其他字符序列。

s = 'these,words,are,separated,by,comma'
print('\',\' separated split -> {}'.format(s.split(',')))

s = 'abacbdebfgbhhgbabddba'
print('\'b\' separated split -> {}'.format(s.split('b')))
',' separated split -> ['these', 'words', 'are', 'separated', 'by', 'comma']
'b' separated split -> ['a', 'ac', 'de', 'fg', 'hhg', 'a', 'dd', 'a']

將列表元素加入字符串

需要與上述相反的操作嗎?join()您可以使用該方法將列表元素字符串連接成 Python 中的單個字符串。

s = ['KDnuggets', 'is', 'a', 'fantastic', 'resource']

print(' '.join(s))
KDnuggets is a fantastic resource

這不就是事實嗎!如果你想在列表元素之間加入空格以外的東西?這件事可能有點陌生,但也很容易做到。

s = ['Eleven', 'Mike', 'Dustin', 'Lucas', 'Will']

print(' and '.join(s))
Eleven and Mike and Dustin and Lucas and Will

反轉字符串

Python 沒有內置的字符串反轉方法。然而,考慮到字符串可以像列表一樣被切片,反轉一個可以以與反轉列表元素相同的簡潔方式完成。

s = 'KDnuggets'

print('The reverse of KDnuggets is {}'.format(s[::-1]))
The reverse of KDnuggets is: steggunDK

轉換大寫和小寫

案例之間的轉換可以使用upper()lower()swapcase()方法完成。

s = 'KDnuggets'

print('\'KDnuggets\' as uppercase: {}'.format(s.upper()))
print('\'KDnuggets\' as lowercase: {}'.format(s.lower()))
print('\'KDnuggets\' as swapped case: {}'.format(s.swapcase()))
'KDnuggets' as uppercase: KDNUGGETS
'KDnuggets' as lowercase: kdnuggets
'KDnuggets' as swapped case: kdNUGGETS

檢查字符串成員資格

在 Python 中檢查字符串成員的最簡單方法是使用in運算符。語法非常類似於自然語言。

s1 = 'perpendicular'
s2 = 'pen'
s3 = 'pep'

print('\'pen\' in \'perpendicular\' -> {}'.format(s2 in s1))
print('\'pep\' in \'perpendicular\' -> {}'.format(s3 in s1))
'pen' in 'perpendicular' -> True
'pep' in 'perpendicular' -> False

如果您對在字符串中查找子字符串的位置更感興趣(而不是簡單地檢查是否包含子字符串),那麼 find() 字符串方法會更有幫助。

s = 'Does this string contain a substring?'

print('\'string\' location -> {}'.format(s.find('string')))
print('\'spring\' location -> {}'.format(s.find('spring')))
'string' location -> 10
'spring' location -> -1

find()默認返回子字符串第一次出現的第一個字符的索引,-1如果沒有找到子字符串則返回。檢查文檔以了解對此默認行為的可用調整。

替換子串

如果你想替換子字符串,而不是僅僅找到它們怎麼辦?Pythonreplace()字符串方法會解決這個問題。

s1 = 'The theory of data science is of the utmost importance.'
s2 = 'practice'

print('The new sentence: {}'.format(s1.replace('theory', s2)))
The new sentence: The practice of data science is of the utmost importance.

如果相同的子字符串多次出現,可選的 count 參數可以指定要進行的最大連續替換次數。

組合多個列表的輸出

有多個要以某種元素方式組合在一起的字符串列表嗎?功能沒有問題zip()

countries = ['USA', 'Canada', 'UK', 'Australia']
cities = ['Washington', 'Ottawa', 'London', 'Canberra']

for x, y in zip(countries, cities):
  print('The capital of {} is {}.'.format(x, y))
The capital of USA is Washington.
The capital of Canada is Ottawa.
The capital of UK is London.
The capital of Australia is Canberra.

檢查字謎

想檢查一對字符串是否是彼此的字謎?從算法上講,我們需要做的就是計算每個字符串中每個字母的出現次數,並檢查這些次數是否相等。使用模塊的Countercollections很簡單。

from collections import Counter
def is_anagram(s1, s2):
  return Counter(s1) == Counter(s2)

s1 = 'listen'
s2 = 'silent'
s3 = 'runner'
s4 = 'neuron'

print('\'listen\' is an anagram of \'silent\' -> {}'.format(is_anagram(s1, s2)))
print('\'runner\' is an anagram of \'neuron\' -> {}'.format(is_anagram(s3, s4)))
'listen' an anagram of 'silent' -> True
'runner' an anagram of 'neuron' -> False

檢查回文

如果你想檢查給定的單詞是否是回文呢?從算法上講,我們需要創建單詞的反轉,然後使用==運算符檢查這兩個字符串(原始字符串和反向字符串)是否相等。

def is_palindrome(s):
  reverse = s[::-1]
  if (s == reverse):
    return True
  return False

s1 = 'racecar'
s2 = 'hippopotamus'

print('\'racecar\' a palindrome -> {}'.format(is_palindrome(s1)))
print('\'hippopotamus\' a palindrome -> {}'.format(is_palindrome(s2)))
'racecar' is a palindrome -> True
'hippopotamus' is a palindrome -> False

來源:  https ://www.kdnuggets.com

#python #cheatsheet 

What is GEEK

Buddha Community

使用 Python Cheatsheet 在基本級別操作和處理字符串
Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Ray  Patel

Ray Patel

1626944751

Learning Python: A Cheatsheet for Beginners🔥

Cheatsheets are good when you want to revise some of the concepts but not an idle way to start learning.

#Theory

  • Python is a scripting language.
  • Scripting vs. Compiled? - Language like c++/java’s code needs to be compiled by its compiler. After compilation, it is just machine-level code. Whereas in a scripting language, its interpreter will be run the code on the spot one line at a time.

#VSCODE extension:

  • Python
  • Python for vscode
  • Magic Python
  • Arepl

#Making a virtual env:

#Why Virtual env?

Because managing python dependencies is a mess, this will install dependencies for that project only instead of globally.

  • python -m venv venv this will create a venv folder in your directory.
  • source ./venv/bin/activate this will activate this virtual env.

#Comments in python

  • single-line use #

None

Bash

CSS

C

C#

Go

HTML

Java

JavaScript

JSON

PHP

Powershell

Python

Ruby

SQL

TypeScript

YAML

Copy

## single line comments
  • multiline use '''. often called as docstring, as it is just to document function/classes.

None

Bash

CSS

C

C#

Go

HTML

Java

JavaScript

JSON

PHP

Powershell

Python

Ruby

SQL

TypeScript

YAML

Copy

'''
This is a example of 
Multiline comment.
'''

#Data Types:

  • int ## Whole Numbers
  • float ## Number with decimals.
  • str ## String
  • list ## ordered sequence of object
  • dict ## unordered key-value pairs.
  • tup ## ordered immutable seq. of objects.
  • set ## Unordered collection of unique objs.
  • bool ## Logical value True / False.
  • None ## no value

#python #cheatsheet #python-cheatsheet #coding-skills #programming #python-tutorials #learn-python #programming-language

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

Art  Lind

Art Lind

1602666000

How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.

Intro

In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips