A new era of programming: Amazon CodeWhisperer helps you easily navigate the world of code

Insert image description here

1. What is Amazon CodeWhisperer?

Amazon CodeWhisperer is a code generator powered by machine learning that provides code suggestions in real time. When writing code in the IDE, CodeWhisperer automatically generates suggestions based on your comments and existing code.

It supports 15 programming languages, including Python, Java, and JavaScript, as well as your favorite integrated development environments (IDEs), including VS Code, IntelliJ IDEA, AWS Cloud9, AWS Lambda Console, JupyterLab, and Amazon SageMaker Studio.
Insert image description here

Here's how Amazon's CodeWhisperer tool generates code based on text input:
Insert image description here
Amazon CodeWhisperer demonstrates good fluency in both PyCharm and VSCode. Whether inserting code or switching different functions, the response speed is very fast without any lag or delay, providing users with a pleasant programming experience.

2. Unlimited free use for individuals

It is worth mentioning that CodeWhisperer provides free personal packages for individual developers. With a simple registration and login using your email and AWS Builder ID, individual developers can start enjoying the convenience of CodeWhisperer within minutes. The personal package not only provides code suggestion functions, but also includes practical functions such as reference tracking and security scanning, which fully meets the various needs of individual developers in the programming process.
Insert image description here

Next, we'll detail how to configure and use CodeWhisperer in different programming environments.

3. Installation and configuration

The process of installing Amazon CodeWhisperer in PyCharm and VSCode is very simple and intuitive. Users only need to search and install "AWS Toolkit" in the plug-in market, without complex configuration. This allows users to get started quickly without spending too much time on installation and configuration.

3.1 Teach you step by step how to configure pycharm

The process of installing Amazon CodeWhisperer in PyCharm and VSCode is very simple and intuitive. Users only need to search and install "AWS Toolkit" in the plug-in market, without complex configuration. This allows users to get started quickly without spending too much time on installation and configuration.

Let’s take a look at Amazon CodeWhisperer. I'll demonstrate how to use it in PyCharm (besides that it also supports other editors like VS etc.). First, you need to download the plug-in: AWS Toolkit. Enter settings:

Your Image

After entering the settings, we can see that the interface of the plug-in market is very intuitive. After searching for "AWS Toolkit", click "install" to install.

Insert image description here
Select "apply" and click "OK":

Then click Restart:

After installation and restart, we can see the CodeWhisperer option in the AWS Toolkit view (menu View/Tool Windows/AWS Toolkit), which indicates that we have successfully installed and can start using it.
Insert image description here
Then, click the "Developer Tools" tab page and select "CodeWhisperer/Start", as shown in the figure below: The
Insert image description here
interface will pop up, click "open and Copy Code"
Insert image description here
to paste and submit:
Insert image description here
Next, you need to log in to your account:
Insert image description here
Enter your password:
Insert image description here
At this time The interface "Allow AWS Toolkit for JetBrains to access your data?" will pop up, as shown below. Click "Allow": it
Insert image description here
will display "AWS Toolkit for JetBrains can now access your data. You can close this window and start using AWS Toolkit for JetBrains. ” means that the connection can be made normally and the configuration is successful!
Insert image description here
Return to pycharm and you can see that it has been enabled:
Insert image description here

3.2 Install in VSCODE in the same way

In VSCode, we can also easily find and install "AWS Toolkit" in the plug-in market. The installation process is similar to that in PyCharm, very simple and intuitive.
Insert image description here
Select the second one:
Insert image description here
Continue:
Insert image description here
Click Allow:
Insert image description here
Configuration successful:
Insert image description here

After the installation is successful, the VSCode interface also displays the related options of CodeWhisperer, which means that we can start using CodeWhisperer in VSCode.
Insert image description here

3. Test on Pycharm

Using Amazon CodeWhisperer in PyCharm also shows good operational convenience. Users only need to write comments according to their needs, and CodeWhisperer will automatically pop up code suggestions, and users can easily select and insert code. The process is simple and straightforward, so even novice programmers can get started quickly.

3.1 Write code based on comments

In PyCharm we can easily generate code based on comments. For example, I wrote a comment "Grab the price of iPhone 15 from Amazon Mall", and Amazon CodeWhisperer will automatically pop up an interface for suggested codes, and we can select the appropriate code to insert.
Insert image description here
They stand for "Insert Code", "Previous Option", and "Next Option" respectively. Because it will automatically provide us with reference codes, just select a suitable code and click to insert it.

After inserting the code each time, press the space button on the keyboard to continue inserting the code. Just follow the prompts to continue inserting the code.

This function is very practical, especially when completing algorithm questions. By constantly "space" and "Insert Code", we can easily complete the code in a few seconds.

Let's complete an algorithm assignment below:

# 输出:按照从小到大排序后的列表。
#
# 示例:
# 输入:[5, 3, 8, 2, 1]
# 输出:[1, 2, 3, 5, 8]

By continuously "space" and "lnsert Code", you can easily complete the code in a few seconds as follows:

def ipserch(arr):
    for i in range(len(arr)):  # 冒检
        for j in range(i, len(arr)):
            if arr[i] > arr[j]:
                arr[i], arr[j] = arr[j], arr[i]  # 位置修�]
    return arr


if __name__ == "__main__":
    arr = [5, 3, 8, 2, 1]
    print(ipserch(arr))

The running result is completely correct, as shown in the figure:
Insert image description here
Let's complete a homework exercise: an integer, after adding 100, it becomes a perfect square number, and when added to 168, it becomes a perfect square number. What is this number? Please use python to implement it. As shown below:
Insert image description here
Give the standard answer directly, which is great!

3.2 Check and fix code errors

While using Amazon CodeWhisperer, I also tested and evaluated its performance in terms of code security. CodeWhisperer is not only able to generate high-quality code, but also has the ability to identify it. The following is a simple identification and repair code.

This is the code I started with, deliberately leaving an error here:
Insert image description here
execute CodeWhisperer to automatically fix it:
Insert image description here

3.3 Build a simple crawler

When building a web crawler, we only need to write the requirements in the comments, and Amazon CodeWhisperer can generate the corresponding code for us, which greatly improves development efficiency.

# 写一个爬虫,模拟打开百度,输入“川川菜鸟”并回车 
# 然后点第一个页面进去查看  
# 用selenium框架 

Get the following:

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
time.sleep(3)
driver.find_element_by_id("kw").send_keys("川川菜鸟") # 输入内容
driver.find_element_by_id("su").click() # 点击搜索

Next, continue to write the requirements in the comments. Just keep writing the comments clearly and get the corresponding code:

from selenium import webdriver
import time
from selenium.webdriver.common.by import By


driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
time.sleep(3)
driver.find_element(By.ID,'kw').send_keys("川川菜鸟")  # 输入内容
driver.find_element(By.ID,'su').click()  # 点击
# 鼠标滑动180度
js = 'document.documentElement.scrollTop=180'
driver.execute_script(js)
time.sleep(3)

4. Test on VSCODE

Similar to PyCharm, Amazon CodeWhisperer on VSCODE is also easy to operate. After running CodeWhisperer through the shortcut key "Alt+c", users can easily generate code based on comments, check code errors, and try new programming languages. This convenient operation method greatly reduces the user's difficulty in getting started and improves programming efficiency.

4.1 Personalized experience

During use, Amazon CodeWhisperer demonstrates a very good personalized experience. It can remember my programming style and provide appropriate code suggestions based on my habits, which makes me feel very comfortable and greatly improves my programming efficiency.

4.2 System compatibility

I tested the performance of Amazon CodeWhisperer in PyCharm and VSCode on Windows systems, and found that it can run stably in both IDEs, integrates perfectly with the IDE, and shows good system compatibility.

4.3 Write code based on comments

As shown below, first let it write a function according to my requirements, and then write an example.

# 写一个求两数和
def add(a,b):
    return a+b
# 给个示例
print(add(1,2))

4.4 Try a new language

With the help of Amazon CodeWhisperer, I tried to learn C++ and successfully completed some basic exercises. This tool provided me with rich sample code and real-time suggestions, allowing me to quickly get started in a new programming language.
Insert image description here
Enter 3 numbers and find the maximum value:

Insert image description here

4.5 Code generation quality

While using Amazon CodeWhisperer, I particularly noticed the quality of the code it generates. Whether it is completing algorithm questions or building web crawler applications, the code generated by CodeWhisperer shows a high standard.

Comply with programming standards:
The generated code has a clear structure, standardized naming, and conforms to the programming standards of Python and C++, which makes the code easy to understand and facilitates subsequent code maintenance. For example, when generating sorting algorithm and web crawler codes, the functions are clearly named, the logical structure is reasonable, and the indentation and blank lines between codes are also in compliance with the standards, showing CodeWhisperer's compliance with programming standards.

Readability:
CodeWhisperer generates code that is highly readable. The code logic is clear and fully commented. Even novice programmers can quickly understand the function and operating mechanism of the code. This was especially evident when I was trying to learn the new programming language C++. CodeWhisperer's code suggestions helped me quickly understand the syntax and structure of C++.

Maintainability:
The generated code has a high degree of modularity and reasonable function division, which makes the code highly maintainable. Even if the code needs to be modified and expanded later, it can be easily done, greatly improving development efficiency.

5. Practical web crawler: crawling csdn hot list data

Comments are provided as follows:

# 使用selenium爬取热榜
# 热榜地址:https://blog.csdn.net/rank/list
# 获取标题、浏览量、评论数量、收藏数量

During the first execution, relevant modules will be automatically inserted, eliminating the need to manually type, saving time.

from selenium import webdriver
import time
import csv
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Continue to execute CodeWhisperer and write a request function to open the web page:

def get_data(url):
    driver = webdriver.Chrome()
    driver.get(url)
    time.sleep(5)

Our goal is to obtain the corresponding data, so add comments and execute CodeWhisperer

# 打开热榜地址

Insert the code as follows:
Insert image description here
What do you do after opening it? Get the title, page views, number of comments, and number of collections, so add comments as follows and execute CodeWhisperer

#添加等待10秒

As shown below:
Insert image description here
Keep adding comments:

# 等待直到页面加载完成

# 获取所有的文章元素

# 创建或打开CSV文件,准备写入数据:浏览量、评论数量、收藏数量

Execute CodeWhisperer, as shown below:
Insert image description here
Obtaining all elements requires manual adjustment, positioning, viewing, and copying them out:
Insert image description here
Next, you need to traverse to obtain all content and add comments:

 # 遍历所有文章元素,提取所需数据:浏览量、评论数量、收藏数量

Execute CodeWhisperer and insert the code as follows:
Insert image description here
In the same way, the positioning element needs to be adjusted manually. Here you can see an example of title positioning. The same is true for other things:
Insert image description here
continue to execute CodeWhisperer to complete some remaining code. The complete code is as follows:

def get_data(url):
    driver = webdriver.Chrome()
    driver.get(url)
    # 添加等待
    wait = WebDriverWait(driver, 10)
    try:
        # 等待直到页面加载完成
        wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.hostitem.floor")))
        # 获取所有的文章元素
        product_elements = driver.find_elements(By.CSS_SELECTOR, "div.hostitem.floor")
        # 创建或打开CSV文件,准备写入数据:浏览量、评论数量、收藏数量
        with open('output.csv', mode='w', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerow(["Title", "View", "Comment", "Collect"])  # 写入表头
            # 遍历所有文章元素,提取所需数据:浏览量、评论数量、收藏数量
            for index, product in enumerate(product_elements):
                title = product.find_element(By.CSS_SELECTOR, "div.hosetitem-title > a").text
                view = product.find_element(By.CSS_SELECTOR, "div.hosetitem-dec > span:nth-child(1)").text
                comment = product.find_element(By.CSS_SELECTOR, "div.hosetitem-dec > span:nth-child(3)").text
                collect = product.find_element(By.CSS_SELECTOR, "div.hosetitem-dec > span:nth-child(5)").text
                # 打印到控制台
                print(f"Product {index + 1}:")
                print(f"Title: {title}")
                print(f"View: {view}")
                print(f"Comment: {comment}")
                print(f"Collect: {collect}")
                # 写入到CSV文件
                writer.writerow([title, view, comment, collect])
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # 确保关闭WebDriver,释放资源
        driver.quit()

The output result is as follows, only 25 pieces of data were captured:
Insert image description here
I found that I only got 25 pieces of data when crawling the web page. If you want to get the following content, you need to scroll down to load the data from 25 to 50. In the same way, you can continue to scroll. Load data from 25 to 75. In order to load more data, it is necessary to simulate scrolling the page to complete. So the idea is: scroll and load all the data first, and then crawl it.

Add a comment to get all article elements:

# 滚动页面以加载更多数据

As follows:
Insert image description here
At this point we can see that all data capture has been completed:
Insert image description here
saved in the csv file as follows:
Insert image description here

With the help of CodeWhisperer, I really save a lot of time writing code, and I have more time to fish ~

The complete code is as follows:

# 书籍介绍·:https://chuanchuan.blog.csdn.net/article/details/133050678
# 使用selenium爬取热榜
# 热榜地址:https://blog.csdn.net/rank/list
# 获取标题、浏览量、评论数量、收藏数量


from selenium import webdriver
import time
import csv
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def get_data(url):
    driver = webdriver.Chrome()
    driver.get(url)
    # 添加等待
    wait = WebDriverWait(driver, 10)
    try:
        # 等待直到页面加载完成
        wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.hostitem.floor")))

        # 滚动页面以加载更多数据
        for _ in range(4):
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(5)


        # 获取所有的文章元素
        product_elements = driver.find_elements(By.CSS_SELECTOR, "div.hostitem.floor")
        # 创建或打开CSV文件,准备写入数据:浏览量、评论数量、收藏数量
        with open('output.csv', mode='w', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerow(["Title", "View", "Comment", "Collect"])  # 写入表头
            # 遍历所有文章元素,提取所需数据:浏览量、评论数量、收藏数量
            for index, product in enumerate(product_elements):
                title = product.find_element(By.CSS_SELECTOR, "div.hosetitem-title > a").text
                view = product.find_element(By.CSS_SELECTOR, "div.hosetitem-dec > span:nth-child(1)").text
                comment = product.find_element(By.CSS_SELECTOR, "div.hosetitem-dec > span:nth-child(3)").text
                collect = product.find_element(By.CSS_SELECTOR, "div.hosetitem-dec > span:nth-child(5)").text
                # 打印到控制台
                print(f"排名:{index + 1}")
                print(f"标题: {title}")
                print(f"浏览量: {view}")
                print(f"评论量: {comment}")
                print(f"收藏量: {collect}")
                # 写入到CSV文件
                writer.writerow([title, view, comment, collect])
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # 确保关闭WebDriver,释放资源
        driver.quit()

url='https://blog.csdn.net/rank/list'
get_data(url)

6. Official documents

For users who have an in-depth understanding and mastery of CodeWhisperer, the official documentation is an excellent learning material. The document lists detailed descriptions of various functions, operation screenshots and practical demonstrations, helping users to fully and deeply understand and use CodeWhisperer. For more usage methods and related operations, please refer to the official documentation: CodeWhisperer . There are detailed usage tutorials, screenshots and demonstrations to help developers use it better:
Insert image description here
the website provides a wealth of usage tutorials, actual screenshots and Demonstration helps developers use the tool more conveniently and efficiently.

Guess you like

Origin blog.csdn.net/weixin_46211269/article/details/133291804